/**
 * Created by bolin on 2016/12/22.
 */
/*
common
 */
var Guid = {
    NewGuid: function () {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
}
//从数组中删除指定ID的项
Array.prototype.Remove = function (dx) {
    var me = this;
    if (me.splice != undefined) {
        var i = 0;
        var tmp = -1;
        $.each(this, function (i, val) {
            if (this.guid == dx.guid)
                tmp = i;
            ++i;
        });
        if (tmp != -1)
            this.splice(tmp, 1);
    }
}
//数组中是否包含指定ID
Array.prototype.contains = function (dx) {
    var i = 0;
    var tmp = -1;
    var flag = false;
    $.each(this, function (i, val) {
        if (this.ID == dx.ID)
            flag = true;
    });
    return flag;
}
//根据属性名和属性值，查找第一个符合条件的对象
Array.prototype.first = function (dx, propName) {
    var i = 0;
    var tmp = undefined;
    var flag = false;
    if (propName == undefined)
        propName = "guid";
    $.each(this, function (i, val) {
        for (var i in this) {
            if (i == propName && this[i] == dx) {
                tmp = this;
                return false;
            }
        }
    });
    return tmp;
}
//根据属性名和属性值，查找第一个符合条件的对象
Array.prototype.findall = function (dx, propName) {
    var i = 0;
    var result = []
    if (propName == undefined)
        propName = "guid";
    $.each(this, function (i, val) {
        for (var i in this) {
            if (i == propName && this[i] == dx) {
                result.push(this);
            }
        }
    });
    return result;
}
CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r, shadow) {


    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;
    this.beginPath();

    //if (shadow != undefined) {
    //    this.save();
    //    this.shadowColor = "rgba(180,180,180,90)";
    //    this.shadowOffsetX = 4;
    //    this.shadowOffsetY = 4;
    //    this.shadowBlur = 3;
    //}
    if (wf.isIe9) {
        x = -x;
        y = -y;


        this.moveTo(x, r - y);
        this.lineTo(x, y - r);
        this.arc(x - r, y - r, r, 0, Math.PI / 2);
        this.lineTo(r - x, y);
        this.arc(r - x, y - r, r, Math.PI / 2, Math.PI);
        this.lineTo(-x, r - y);
        this.arc(r - x, r - y, r, Math.PI, Math.PI * 1.5);
        this.lineTo(x - r, -y);
        this.arc(x - r, r - y, r, Math.PI * 1.5, Math.PI * 2);
        this.closePath();
        this.fillStyle = 'white';
        return this;

    }
    else {
        this.beginPath();
        this.moveTo(x + r, y);
        this.arcTo(x + w, y, x + w, y + h, r);
        this.arcTo(x + w, y + h, x, y + h, r);
        this.arcTo(x, y + h, x, y, r);
        this.arcTo(x, y, x + w, y, r);
        this.closePath();
        this.fillStyle = 'white';
        return this;
    }
}
CanvasRenderingContext2D.prototype.DrawLine = function (point1, point2, style) {

    this.setTransform(1, 0, 0, 1, 0, 0);
    this.strokeStyle = style
    this.beginPath();
    this.moveTo(point1.X, point1.Y);
    this.lineTo(point2.X, point2.Y);
    this.stroke();

}
CanvasRenderingContext2D.prototype.DrawCircle = function (x, y, r, style, isFill, shadow) {

    this.beginPath();
    this.save();
    //if (shadow != undefined) {

    //    this.shadowColor = "rgba(180,180,180,90)";
    //    this.shadowOffsetX = 2;
    //    this.shadowOffsetY = 2;
    //    this.shadowBlur = 3;
    //}
    this.arc(x, y, r, 0, Math.PI * 2, true);
    this.closePath();
    if (isFill == undefined) {
        this.fillStyle = style;
        this.fill();
    }
    else {
        this.strokeStyle = style;
        this.stroke();
    }
    this.restore();
}
/*
 Define
 */
var StyleDefine = {
    activity: {
        'referenceLineStyle': 'rgba(255,0,0,0.8)',
        'capturelength': 10,
        start: {
            'Radius': 15
        },
        end: {
            'Radius': 15
        },
        drafting: {
            'activityRectVertexX': 57.5,
            'activityRectVertexY': 22,
            'activityRectAngle': 8,
            'activityRectWidth': 115,
            'activityRectHeight': 44,
            'imgWidth': 0,
            'imgHeight': 0,
            'font': 12
        },
        approval: {
            'activityRectVertexX': 57.5,
            'activityRectVertexY': 22,
            'activityRectAngle': 11,
            'activityRectWidth': 115,
            'activityRectHeight': 44,
            'imgWidth': 10,
            'imgHeight': 10,
            'font': 12
        },
        condition: {
            'diamondWidth': 57.5,
            'diamondHeight': 22
        }
    },
    arrow: {
        'arrowLength': 15,
        'arrowAngle': 8
    },
    rule: {
        'selectRadius': 7,
        'referenceLineStyle': 'rgba(255,0,0,0.8)',
        'capturelength': 10,
        'strokeStyle': "#0000ff"

    },
    window: {
        'width': 2000,
        'height': 1600
    }
}
var TemplateStatus = {
    None: -1,
    New: 0,
    Open: 1,
    Import: 2

}
var Command = {
    addactivity: 0,
    addrules: 1,
    nulloperation: 3,
    moveactivity: 4,
    moverule: 5,
    selectactivity: 2,
    selectrule: 8,
    zoomin: 6,
    zoomout: 7,
    movecanvas: 9,
    save: 10,
    copy: 11,
    paste: 12,
    delete: 13,
    undo: 14,
    redo: 15,
    create: 16,
    autoadjust: 17,
    showactivitypropertyconfig: 18,
    showrulepropertyconfig: 19,
    deleteactivity: 20,
    deleterule: 21,
    open: 22,
    syncx: 23,
    syncy: 24,
    export: 25,
    import: 26,
    lock: 27
}
var ActivityType = {
    /// <summary>
    /// 开始节点
    /// </summary>
    'start': 0,
    /// <summary>
    /// 结束
    /// </summary>
    'end': 1,
    /// <summary>
    /// 起草节点
    /// </summary>
    'drafting': 2,

    /// <summary>
    /// 条件分支
    /// </summary>
    'condition': 3,

    /// <summary>
    /// 审批节点（包含并行和串行两种模式）
    /// </summary>
    'approval': 4,
    /// <summary>
    /// 审阅节点
    /// </summary>
    'freedom': 4,

    /// <summary>
    /// 分支
    /// </summary>
    'work': 5,
    /// <summary>
    /// 合并
    /// </summary>
    'freedom': 6,
    /// <summary>
    /// 子流程
    /// </summary>
    'subprocesses': 7

}
var ActivityPropertyStatus = {
    /// <summary>
    /// 是否编辑表单
    /// </summary>
    ENABLE_EDIT_ATTACHMENT: "0|2",
    //是否添加附件
    ENABLE_ATTACHMENT: "2|2",
    /// <summary>
    /// 是否查看审批历史
    /// </summary>
    ENABLE_SHOW: "4|2",
    /// <summary>
    /// 是否提交意见
    /// </summary>
    ENABLE_SUGGESTION: "6|2",
    /// <summary>
    /// 是否需要签名
    /// </summary>
    ENABLE_SIGNATURE: "8|2",
    /// <summary>
    /// 是否终止流程
    /// </summary>
    ENABLE_TERMINATE_FLOW: "10|2",
    /// <summary>
    /// 合并审批节点
    /// </summary>
    IS_MERGR: "12|2",
    /// <summary>
    /// 是否转批
    /// </summary>
    ENABLE_TRANSFER: "14|2",
    /// <summary>
    /// 是否传阅
    /// </summary>
    ENABLE_CIRCULATED: "16|2",
    /// <summary>
    /// 是否归档
    /// </summary>
    ENABLE_FILED: "18|2",
    /// <summary>
    /// 是否人工决策
    /// </summary>
    IS_ARTIFICIAL_DECISION: "20|2",
    /// <summary>
    /// 选人方式
    /// </summary>
    IS_AUTOMATIC: "22|2",
    /// <summary>
    /// 完成方式
    /// </summary>
    FINISH_TYPE: "24|2",
    /// <summary>
    /// 在线公文打开方式
    /// </summary>
    OPEN_MODE_TYPE: "26|4",
    /// <summary>
    /// 是否限制上传附件
    /// </summary>
    IS_UPLOAD_AUTOMATIC: "30|2"
}
var PropertyConfig = {
    'start': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],
    'end': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],

    'drafting': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    },
        {
            'id': 'UserProperty',
            'description': '人员设置',
            'js': 'UserProperty'
        }],
    'approval': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    },
        {
            'id': 'UserProperty',
            'description': '人员设置',
            'js': 'UserProperty'
        },
        {
            'id': 'ReturnProperty',
            'description': '回退设置',
            'js': 'ReturnProperty'
        }],

    'freedom': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    },
        {
            'UserProperty': 'UserProperty',
            'description': '人员设置',
            'js': 'UserProperty'
        },
        {
            'id': 'ReturnProperty',
            'description': '回退设置',
            'js': 'ReturnProperty'
        }],
    'condition': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],
    'merging': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],
    'branching': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }]
}
/*
helper
 */
function Arrow(p1, p2) {

    angle = StyleDefine.arrow.arrowAngle * Math.PI / 180;
    var upArrow = new Point(-StyleDefine.arrow.arrowLength * Math.cos(angle), StyleDefine.arrow.arrowLength * Math.sin(angle));
    var downArrow = new Point(-StyleDefine.arrow.arrowLength * Math.cos(angle), -StyleDefine.arrow.arrowLength * Math.sin(angle));
    var slope = wf.mathHelper.Angle(p1, p2);
    upArrow.Rotation(slope.sin, slope.cos);
    downArrow.Rotation(slope.sin, slope.cos);
    upArrow.MovePoint(p2);
    downArrow.MovePoint(p2);
    return {
        "upArrow": upArrow,
        "downArrow": downArrow
    }
}

var Point = function (x, y) {
    this.X = parseFloat(x);
    this.Y = parseFloat(y);
    this.MovePoint = function (p) {
        this.X += p.X;
        this.Y += p.Y;
        return this;
    };
    this.Rotation = function (sin, cos) {
        var x = this.X;
        var y = this.Y;
        this.X = x * cos - y * sin;
        this.Y = y * cos + x * sin;
    };
}
var MathHelper = function () {
}
MathHelper.prototype = {
    //两点距离
    PointDistinct: function () {
        var x1;
        var y1;
        var x2;
        var y2;
        if (arguments.length == 2) {
            x1 = arguments[0].X;
            y1 = arguments[0].Y;
            x2 = arguments[1].X;
            y2 = arguments[1].Y;
        }
        else if (arguments.length == 4) {
            x1 = arguments[0];
            y1 = arguments[1];
            x2 = arguments[2];
            y2 = arguments[3];
        }

        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    },
    //计算sin，cos值
    Angle: function (p1, p2) {
        var x = p2.X - p1.X;
        var y = p2.Y - p1.Y;
        //线段长度
        var z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        var sin = 0;
        var cos = 1;
        if (z != 0) {
            var sin = y / z;
            var cos = x / z;
        }
        return {'sin': sin, 'cos': cos};
    },
    //p1鼠标起始位置
    //p2节点原始坐标
    //p3鼠标当前位置
    Move: function (p1, p2, p3) {
        var x = p3.X - p1.X + p2.X;
        var y = p3.Y - p1.Y + p2.Y;
        return new Point(x, y);
    },
    //点p3到由p1,p2构成线段的距离
    GetNearestDistance: function (p1, p2, p3) {
        var a = this.PointDistinct(p2.X, p2.Y, p3.X, p3.Y);
        if (a <= 0.00001)
            return 0;
        var b = this.PointDistinct(p1.X, p1.Y, p3.X, p3.Y);
        if (b <= 0.00001)
            return 0;
        var c = this.PointDistinct(p1.X, p1.Y, p2.X, p2.Y);
        if (c <= 0.00001)
            return a;
        if (a * a >= b * b + c * c)
            return b;
        if (b * b >= a * a + c * c)
            return a;
        var l = (a + b + c) / 2;
        var s = Math.sqrt(l * (l - a) * (l - b) * (l - c));
        return 2 * s / c;
    },
    //p1:节点当前位置
    //p2:鼠标当前位置
    GetIntersectionPoint: function (p1, p2, p3, p4) {
        //坐标平移
        p2 = new Point(p2.X - p1.X, p2.Y - p1.Y);

        var k = 0;
        var b = 0;
        if (p3.X != p4.X) {
            k = (p3.Y - p4.Y) / (p3.X - p4.X);
            b = p3.Y - k * p3.X;
        }

        var a = p2.Y / p2.X;
        var resultX = b / (a - k);
        var resultY = a * resultX;

        return new Point(resultX + p1.X, resultY + p1.Y);


    },
    IsCaptureX: function (currentPosition, point) {
        return this.IsCapture(currentPosition, new Point(point.X, currentPosition.Y), 'x');
    },
    IsCaptureY: function (currentPosition, point) {
        return this.IsCapture(currentPosition, new Point(currentPosition.X, point.Y), 'y');
    },
    IsCapture: function (p1, p2, co) {
        var capture = {
            'iscapture': false,
            'point': new Point(0, 0),
            'dis': 0
        }

        var dis = wf.mathHelper.PointDistinct(p1, p2);
        if (dis < 10) {

            var point;
            if (co == 'x') {

                point = new Point(p2.X, p1.Y);
            }
            else {
                point = new Point(p1.X, p2.Y);
            }
            capture = {
                'iscapture': true,
                'point': point,
                'dis': dis
            }
        }
        return capture;
    },
    LineCircleIntersection: function (center, r, k, p) {


        var l = k * k + 1;
        var m = -2 * k * center.Y - 2 * center.X;
        var n = Math.pow(center.X, 2) + Math.pow(center.Y, 2) - Math.pow(r, 2);
        var dt = m * m - 4 * l * n;

        if (dt >= 0) {
            dt = Math.sqrt(dt);
            var x1 = (-m + dt) / (2 * l);
            var y1 = k * x1;

            var x2 = (-m - dt) / (2 * l);
            var y2 = k * x2;

            var dis1 = this.PointDistinct(x1, y1, p.X, p.Y);
            var dis2 = this.PointDistinct(x2, y2, p.X, p.Y);
            if (dis1 > dis2)
                return new Point(x2, y2);
            else return new Point(x1, y1);

        }
        return null;
    },
    Arrow: function (p1, p2, arrowLength) {
        var me = this;
        angle = StyleDefine.arrow.arrowAngle * Math.PI / 180;

        if (!arrowLength)
            arrowLength = StyleDefine.arrow.arrowLength;
        var upArrow = new Point(-arrowLength * Math.cos(angle), arrowLength * Math.sin(angle));
        var downArrow = new Point(-arrowLength * Math.cos(angle), -arrowLength * Math.sin(angle));
        var slope = me.Angle(p1, p2);
        upArrow.Rotation(slope.sin, slope.cos);
        downArrow.Rotation(slope.sin, slope.cos);
        upArrow.MovePoint(p2);
        downArrow.MovePoint(p2);
        return {
            "upArrow": upArrow,
            "downArrow": downArrow
        }
    }
}
var ActivityHelper = function () {
    this.Activitys = new Array();
}
ActivityHelper.prototype = {
    StartActivity: null,
    EndActivity: null,
    DraftingActivity: null,
    Activitys: [],

    //添加节点
    /*
     e：当前位置信息
     activityType：节点类型
     isload：调用此方法的位置
     1、从画布上手动绘制的
     2、打开或者导入流程时
     默认值 undefined
     当手动绘制时，添加规则操作会记录操作历史。
     */
    AddActivity: function (point, activityType, isload) {
        var me = this;
        // 1、移除窗体上所有空间的样式（被选中）
        wf.canvasHelper
        wf.canvasHelper.ClearAllStyle();
        var canInfo = wf.canvasHelper.InitialCanvas();
        //2、增加节点
        //var point = wf.canvasHelper.GetPoint(e);
        var activity = new Activity(activityType, point, canInfo, isload);
        if (isload == undefined) isload = false;
        if (activityType == ActivityType.branching && !isload) {
            canInfo = wf.canvasHelper.InitialCanvas();
            new Activity(ActivityType.merging, new Point(point.X + 350, point.Y), canInfo);
        }
        if (!wf.isDoubleClickCommand)
            wf.gcommand = Command.nulloperation;
        if (!isload)
            toolbar.HistroyOpertion();
        return activity;
    },

    //获取所有节点的可退回节点
    /*
     此方法为递归方法，初始值为me.DraftingActivity,依此后推
     当节点没有到DraftingActivity的路径时，无法计算出前驱节点
     */
    GetReturnActivitys: function (activity) {
        var me = this;
        activity.LoopCount += 1;
        if (activity.activityType == ActivityType.drafting) {
            $.each(me.Activitys, function (i, val) {
                val.Preactivity = new Array();
            });
        }
        $.each(activity.FromRule, function (i, rule) {
            var ac = rule.endActivity;
            var isContainsNew = false
            if (activity.Preactivity == undefined)
                activity.Preactivity = new Array();
            if (ac.Preactivity.length == 0) {
                isContainsNew = true;
                $.each(activity.Preactivity, function (j, preac) {
                    ac.Preactivity.push(preac);
                });
            }
            else {
                $.each(activity.Preactivity, function (j, preac) {
                    if (!ac.Preactivity.first(preac.guid) && ac.guid != preac.guid) {
                        ac.Preactivity.push(preac);
                        isContainsNew = true;
                    }
                });
            }
            if (ac.Preactivity.first(activity.guid) == undefined) {
                ac.Preactivity.push(activity);
                isContainsNew = true;
            }
            if (isContainsNew)
                me.GetReturnActivitys(rule.endActivity);
        });
    },

    //释放所有的对象
    /*一般用于全新创建流程*/
    Dispose: function () {
        var me = this;
        for (i = me.Activitys.length - 1; i >= 0; --i) {
            if (me.Activitys[i] != undefined)
                me.Activitys[i].Dispose(true);
        }
    }

}
//画布相关操作
var CanvasHelper = function () {
}
CanvasHelper.prototype = {
    //创建流程模版
    CreateTemplate: function () {
        var me = this;
        var flag = true;
        if (wf.activityHelper != undefined)
            flag = confirm("确认新建？");
        if (flag) {
            if (wf.activityHelper == undefined)
                wf.activityHelper = new ActivityHelper();
            wf.activityHelper.Dispose();
            //activitys = new Array();
            wf.rules = new Array();

            var me = this;
            var po = StyleDefine.window.height;
            //初始化节点
            var activity = wf.activityHelper.AddActivity(new Point(50, 50), ActivityType.start);
            wf.activityHelper.StartActivity = activity;
            var rule = new Rule(activity);
            activity = wf.activityHelper.AddActivity(new Point(170, 50), ActivityType.drafting);
            wf.activityHelper.DraftingActivity = activity;
            me.AddRule(rule, activity);
            activity = wf.activityHelper.AddActivity(new Point($(document).width() - 150, $(document).height() - 100), ActivityType.End);
            wf.activityHelper.EndActivity = activity;
            toolbar.InitailSnapshot();
        }
    },
    //清空当前模版
    //Dispose: function () {
    //    activityHelper.Dispose();
    //},
    //添加规则
    /*
     rule：wf.currentRule当前操作的规则
     activity：结束节点
     isload：调用此方法的位置
     1、从画布上手动绘制的
     2、打开或者导入流程时
     默认值 undefined
     当手动绘制时，添加规则操作会记录操作历史。
     */
    AddRule: function (rule, activity, isload) {

        wf.gcommand = Command.nulloperation;
        if (rule.Points.length != 0) {
            var point = rule.GetIntersectionPoint(activity, rule.Points[rule.Points.length - 1]);
            rule.Points[rule.Points.length] = point;
        }
        else {
            var pointE = rule.GetIntersectionPoint(activity, rule.startActivity.position);
            var pointS = rule.GetIntersectionPoint(rule.startActivity, pointE);
            rule.Points[0] = pointS;
            rule.Points[1] = pointE;
        }
        rule.endActivity = activity;
        rule.startActivity.AddFromRule(rule);
        activity.AddToRule(rule);
        wf.rules[wf.rules.length] = rule;
        rule.ResetRule();
        if (isload == undefined)
            toolbar.HistroyOpertion();
    },


    //生成一个新的画布
    InitialCanvas: function () {
        var canvas = $("<canvas>").css({
            'position': 'absolute',
            "z-index": "0",
            'top': '0px',
            "left": "0px"
        }).attr({"width": StyleDefine.window.width, "height": StyleDefine.window.height});
        var cxt = canvas[0].getContext("2d");
        wf.workspace.append(canvas);
        return {
            'canvas': canvas,
            'cxt': cxt
        }
    },


    //获得鼠标当前位置
    GetPoint: function (e) {
        if (e != undefined) {
            if (e.offsetX != undefined)
                return new Point(e.offsetX, e.offsetY);
            else if (e.pageX != undefined) {
                return new Point(e.pageX - 36 + wf.workspace.scrollLeft(), e.pageY + wf.workspace.scrollTop());
            }
            else return e;
        }
        return e;
    },


    //根据鼠标位置获得选中的节点
    /*
     e：当前鼠标信息
     */
    GetSelectedActivity: function (e) {
        var selectedActivitys = new Array();
        var me = this;
        var point = me.GetPoint(e);
        $.each(wf.activityHelper.Activitys, function (i, val) {
            if (val.Picture.isPointInPath(point.X, point.Y)) {
                selectedActivitys[selectedActivitys.length] = val;
            }

        });

        var result = {
            'isSelect': false,
            'selectedObject': null,
            'distinct': -1
        }


        if (selectedActivitys.length > 0) {
            var minDistinct = wf.mathHelper.PointDistinct(selectedActivitys[0].position.X, selectedActivitys[0].position.Y, point.X, point.Y);
            result.selectedObject = selectedActivitys[0];
            result.distinct = minDistinct;
            result.isSelect = true;
            if (selectedActivitys.length > 1) {
                for (i = 1; i < selectedActivitys.length; i++) {
                    var dis = wf.mathHelper.PointDistinct(selectedActivitys[i].position.X, selectedActivitys[i].position.Y, point.X, point.Y);
                    if (dis < minDistinct) {
                        dis = minDistinct;
                        result.selectedObject = selectedActivitys[i];
                        result.distinct = minDistinct;
                    }
                }
            }
        }
        return result;
    },

    //根据鼠标位置获得选中的规则
    /*
     e：当前鼠标信息
     */
    GetSelectedRule: function (e) {
        var me = this;
        var result = {
            'isSelect': false,
            'selectedObject': null,
            'distinct': 1000
        }
        $.each(wf.rules, function (i, val) {
            var tmp = val.IsSelect(me.GetPoint(e));
            if (tmp.isSelect && result.distinct > tmp.distinct)
                result = tmp;
        });
        return result;
    },

    //重绘画布上的节点和规则样式
    ResetControl: function () {
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.ResetActivity();
        });
        $.each(wf.rules, function (i, val) {
            val.ResetRule();
        });
    },
    //重置画布上的节点和规则样式
    ClearAllStyle: function (e) {
        this.ClearActivityStyle(e);
        this.ClearRuleStyle();
    },

    RefreshAllStyle: function () {
        this.RefreshActivity();
        this.RefreshRule();
    },

    ClearActivityStyle: function (e) {
        $.each(wf.activityHelper.Activitys, function (i, activity) {
            activity.ChangeSelectStatus(e);
        });
    },

    RefreshActivity: function (e) {
        var me = this;
        $.each(wf.activityHelper.Activitys, function (i, activity) {
            activity.ChangeSelectStatus();
        });
    },

    RefreshRule: function () {
        $.each(wf.rules, function (i, rule) {
            rule.ResetRule();
        });
    },

    ClearRuleStyle: function () {
        $.each(wf.rules, function (i, rule) {
            rule.ChangeSelectStatus(false);
        });
    },

    DrawMovePoint: function (cxt, point, length, style) {

        var x1 = point.X - length;
        var y1 = point.Y - length;
        cxt.restore();
        cxt.beginPath();
        cxt.setTransform(1, 0, 0, 1, 0, 0);
        cxt.strokeStyle = style;
        cxt.rect(x1, y1, 2 * length, 2 * length);
        cxt.stroke();
    },


    //绘制参考线
    /*
     position当前鼠标位置
     activityId 用来确定是节点移动时的捕捉还是绘制规则时的捕捉
     节点移动时activity为移动节点
     绘制规则时传入空值*/
    GetCaptureActivity: function (method, position, activity) {
        var me = activity;
        var capture = new Array();
        $.each(wf.activityHelper.Activitys, function (i, val) {
            if (activity == undefined || val.guid != activity.guid) {
                var result = wf.mathHelper[method](position, val.position)
                if (result.iscapture) {
                    result.activity = new Array();
                    result.activity[0] = val;
                    capture[capture.length] = result;
                }
            }
        });

        if (capture.length > 0) {
            var tmp = capture[0];

            if (capture.length > 1) {
                for (i = 1; i < capture.length; i++) {
                    if (capture[i].dis < tmp.dis)
                        tmp = capture[i];
                }

            }
            return tmp;
        }
        return null;
    },


    DrawFocus: function (cxt, point) {
        cxt.restore();
        cxt.beginPath();
        cxt.setTransform(1, 0, 0, 1, 0, 0);
        cxt.strokeStyle = "rgba(225,0,0,1)";
        cxt.moveTo(-5 + point.X, -5 + point.Y);
        cxt.lineTo(5 + point.X, 5 + point.Y);
        cxt.moveTo(5 + point.X, -5 + point.Y);
        cxt.lineTo(-5 + point.X, 5 + point.Y);
        cxt.stroke();
    },

    DrawFocusInvoke: function (cxt, activitys) {

        for (i = 0; i < activitys.length; i++) {
            this.DrawFocus(cxt, activitys[i].position);
        }
    }

}
var SqlHelper = {
    GetAllJob: function () {
        var me = this;
        $.request('/admin/sys/job/query/parameter', {}, function (tmp) {
            me.JobList = tmp;
        }, true, false);
    },
    GetAllPackage: function (callbackMethod) {
        var parm = {};
        var me = this;
        $.request('/workflow/package/query/all', parm, function (list) {
            if (typeof callbackMethod == 'function') callbackMethod(list);
        }, false, false);
    },
    GetTemplateById: function (templateId) {
        var me = this;

        var template = {};

        var Data = {id: templateId}
        $.request('/workflow/template/query/id', Data, function (tmp) {

            template = tmp;

            $.each(template.activities, function (i, val) {

                for (i in ActivityPropertyStatus) {
                    var value = val.status;
                    var option = ActivityPropertyStatus[i];
                    var op = option.split('|');
                    op[0] = parseInt(op[0]);
                    op[1] = parseInt(op[1]);
                    var tmp = Math.pow(2, op[1]) - 1;
                    val[i] = tmp & (value >> (op[0]));
                }
            })
        }, false, false);
        return template;
    },
    GetAllTemplate: function (parm) {
        var me = this;
        $.request('/workflow/template/all', parm, function (tmp) {
            me.TemplateList = tmp;
            return tmp;
        }, false, false);
    }
}
/*
class
 */
var Activity = function (activityType, position, canInfo, isload) {
    this.activityType = activityType;
    this.guid = Guid.NewGuid();
    this.ActivityProperty = {};
    this.ActivityProperty.guid = this.guid;
    this.ActivityProperty.ENABLE_RETURN = 0;
    this.ActivityProperty.ENABLE_RETURN_BY_PREVIOUS_PATH = 0;
    this.ActivityProperty.ENABLE_TRANSIT = 0;
    this.ActivityProperty.IS_ARTIFICIAL_DECISION = 0;
    this.ActivityProperty.IS_AUTOMATIC = 0;
    this.ActivityProperty.ENABLE_REMEMBER_DELIVER_PATH = 0;
    this.ActivityProperty.ENABLE_DELETE_SUB_FLOW = 0;
    this.ActivityProperty.FINISH_TYPE = 0;
    this.ActivityProperty.SUB_FLOW_TYPE = 0;
    this.ActivityProperty.FINISH_NUMBER = 0;
    this.ActivityProperty.activityType = activityType;
    this.ActivityProperty.isDel = 0;
    this.isDrawRuleStart = false;
    this.isDrawRule = false;
    this.position = position;
    this.Canvas = canInfo.canvas;
    this.Picture = canInfo.cxt;
    this.capture = {
        'iscapture': false,
        'point': new Point(0, 0)
    };
    switch (activityType) {
        case ActivityType.start:
            this.ActivityName = "开始";
            break;
        case ActivityType.drafting:
            this.ActivityName = "起草";
            break;
        case ActivityType.approval:
            this.ActivityName = "审批";
            break;
        case ActivityType.freedom:
            this.ActivityName = "自由";
            break;
        case ActivityType.branching:
            this.ActivityName = "分支";
            break;
        case ActivityType.merging:
            this.ActivityName = "合并";
            break;
        case ActivityType.subprocesses:
            this.ActivityName = "子流程";
            break;
        case ActivityType.condition:
            this.ActivityName = "条件";
            break;
        case ActivityType.end:
            this.ActivityName = "结束";
            break;
    }
    this.ClearModel = {};
    this.InitialClearModel();
    this.FromRule = new Array();
    this.ToRule = new Array();
    this.status = 2;
    this.isSelect = 2;
    wf.activityHelper.Activitys[wf.activityHelper.Activitys.length] = this;
    wf.activityHelper.Activitys[wf.activityHelper.Activitys.length - 1].ResetActivity();
    this.BranchingControl = null;
    this.MergingControl = null;
    this.ActivityProperty.activityName = this.ActivityName;
    if (isload == undefined && activityType == ActivityType.merging) {

        this.BranchingControl = wf.activityHelper.Activitys[wf.activityHelper.Activitys.length - 2];
        wf.activityHelper.Activitys[wf.activityHelper.Activitys.length - 2].MergingControl = this;
    }
}
Activity.prototype = {
    //更换ID
    /*应用场景：当打开一个流程，并在该流程的基础上编辑流程，并将编辑后的流程保存为一个全新的流程时，
     需要对原来流程中节点、规则等对象更换ID*/
    ChangeID: function () {
        var me = this;
        var tempActivityID = me.guid;
        me.guid = Guid.NewGuid();
        this.ActivityProperty.guid = me.guid;
        //RETURN
        if (me.ActivityProperty.WF_RULE != undefined) {
            $.each(me.ActivityProperty.WF_RULE, function (i, returnDto) {
                returnDto.id = Guid.NewGuid();
                returnDto.fromGuid = me.guid;
            });
            $.each(wf.activityHelper.Activitys, function (i, val) {
                if (val.ActivityProperty.WF_RULE != undefined && val.guid != me.guid) {
                    $.each(val.ActivityProperty.WF_RULE, function (j, returnDto) {
                        if (returnDto.toGuid == tempActivityID)
                            returnDto.toGuid = me.guid;
                    })
                }
            });
        }
        //PARTICIPANT
        if (me.ActivityProperty.activityParticipants != undefined) {
            $.each(me.ActivityProperty.activityParticipants, function (i, val) {
                val.guid = me.guid;
            });
        }
    },
    //设置节点的属性
    /*打开流程时，将节点的属性加载到系统中
     property：从数据库中读出的节点实体
     */
    SetProperty: function (property) {
        var me = this;
        this.ActivityProperty = property;
        if (property.guid != undefined)
            this.guid = property.guid;

        this.ActivityName = property.activityName
        //针对导入操作，如果模版中角色不存在当前系统中，则删除已选的角色
        if (me.ActivityProperty != undefined && me.ActivityProperty.activityParticipants != undefined) {
            var totalLength = me.ActivityProperty.activityParticipants.length - 1;
            for (h = totalLength; h >= 0; h--) {
                var isRemove = me.ActivityProperty.activityParticipants[h].type == 0;
                if (isRemove) {
                    $.each(SqlHelper.JobList, function (i, val) {
                        {
                            if (val.id == me.ActivityProperty.activityParticipants[h].participantId) {
                                isRemove = false;
                                return false;
                            }
                        }
                    });
                    if (isRemove)
                        me.ActivityProperty.activityParticipants.splice(h, 1);
                }
            }
        }

    },


    //在屏幕上绘制输出当前节点
    /*position：节点位置
     strokeStyle：边线样式
     fillStyle：填充样式
     */
    Draw: function (position, strokeStyle, fillStyle) {

        var activity = this;
        var cxt = this.Picture;
        activity.clearActivity();
        cxt.setTransform(1, 0, 0, 1, position.X, position.Y);
        cxt.strokeStyle = strokeStyle;
        switch (activity.activityType) {
            case ActivityType.approval: {
                activity.DrawRect(cxt, position, StyleDefine.activity.approval.activityRectVertexX, StyleDefine.activity.approval.activityRectVertexY, StyleDefine.activity.approval.activityRectWidth, StyleDefine.activity.approval.activityRectHeight, StyleDefine.activity.approval.activityRectAngle, StyleDefine.activity.approval.imgWidth, StyleDefine.activity.approval.imgHeight, strokeStyle, fillStyle, 'Approval');
            }
                break;
            case ActivityType.drafting: {
                activity.DrawRect(cxt, position, StyleDefine.activity.drafting.activityRectVertexX, StyleDefine.activity.drafting.activityRectVertexY, StyleDefine.activity.drafting.activityRectWidth, StyleDefine.activity.drafting.activityRectHeight, StyleDefine.activity.drafting.activityRectAngle, StyleDefine.activity.drafting.imgWidth, StyleDefine.activity.drafting.imgHeight, strokeStyle, fillStyle, 'Drafting');
            }
                break;
            case ActivityType.condition:
                activity.DrawDiamond(cxt, position, strokeStyle, fillStyle, StyleDefine.activity.condition.diamondWidth, StyleDefine.activity.condition.diamondHeight);
                break;
            case ActivityType.branching:
                activity.DrawDiamond(cxt, position, strokeStyle, fillStyle, StyleDefine.activity.branching.diamondWidth, StyleDefine.activity.branching.diamondHeight);
                break;
            case ActivityType.merging:
                activity.DrawDiamond(cxt, position, strokeStyle, fillStyle, StyleDefine.activity.merging.diamondWidth, StyleDefine.activity.merging.diamondHeight);
                break;
            case ActivityType.start: {
                var grd = cxt.createRadialGradient(-5, -5, 2, 0, 0, StyleDefine.activity.start.Radius);
                grd.addColorStop(0, "white");
                grd.addColorStop(1, "green");
                activity.DrawCircle(cxt, StyleDefine.activity.start.Radius, grd);
            }
                break;
            case ActivityType.end:
                var grd = cxt.createRadialGradient(-5, -5, 2, 0, 0, StyleDefine.activity.end.Radius);
                grd.addColorStop(0, "white");
                grd.addColorStop(1, "red");

                this.DrawCircle(cxt, StyleDefine.activity.end.Radius, grd);
                break;
            case ActivityType.freedom:
                this.DrawFreedom(StyleDefine.activity.end.Radius);
                //this.DrawCircle(cxt, StyleDefine.activity.end.Radius/2, 'rgba(225,0,0,255)');
                break;
        }
    },

    //清除图形的范围
    /*canvas重绘节点（比如拖动节点）时，需要先清除画布上原有图形，该方法用于定义清除画布上清除图像的范围*/
    InitialClearModel: function () {
        var me = this;
        me.ClearModel.offset = 2;
        switch (me.activityType) {
            case ActivityType.start:
                me.ClearModel.startPointX = -StyleDefine.activity.start.Radius - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.start.Radius - me.ClearModel.offset;
                me.ClearModel.width = me.ClearModel.heigth = 2 * StyleDefine.activity.start.Radius;
                break;
            case ActivityType.drafting:
                me.ClearModel.startPointX = -StyleDefine.activity.drafting.activityRectVertexX - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.drafting.activityRectVertexY - me.ClearModel.offset;
                me.ClearModel.width = 2 * StyleDefine.activity.drafting.activityRectVertexX;
                me.ClearModel.heigth = 2 * StyleDefine.activity.drafting.activityRectVertexY;
                break;
            case ActivityType.approval:
                me.ClearModel.startPointX = -StyleDefine.activity.approval.activityRectVertexX - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.approval.activityRectVertexY - me.ClearModel.offset;
                me.ClearModel.width = 2 * StyleDefine.activity.approval.activityRectVertexX;
                me.ClearModel.heigth = 2 * StyleDefine.activity.approval.activityRectVertexY;
                break;
            case ActivityType.freedom:
                me.ClearModel.startPointX = -StyleDefine.activity.start.Radius - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.start.Radius - me.ClearModel.offset;
                me.ClearModel.width = me.ClearModel.heigth = 2 * StyleDefine.activity.start.Radius;
                break;
            case ActivityType.branching:
                me.ClearModel.startPointX = -StyleDefine.activity.branching.diamondWidth - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.branching.diamondHeight - me.ClearModel.offset;
                me.ClearModel.width = 2 * StyleDefine.activity.branching.diamondWidth;
                me.ClearModel.heigth = 2 * StyleDefine.activity.branching.diamondHeight;
                break;
            case ActivityType.merging:
                me.ClearModel.startPointX = -StyleDefine.activity.merging.diamondWidth - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.merging.diamondHeight - me.ClearModel.offset;
                me.ClearModel.width = 2 * StyleDefine.activity.merging.diamondWidth;
                me.ClearModel.heigth = 2 * StyleDefine.activity.merging.diamondHeight;
                break;
            case ActivityType.Subprocesses:
                me.ClearModel.startPointX = -StyleDefine.activity.merging.diamondWidth - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.merging.diamondHeight - me.ClearModel.offset;
                me.ClearModel.width = 2 * StyleDefine.activity.merging.diamondWidth;
                me.ClearModel.heigth = 2 * StyleDefine.activity.merging.diamondHeight;
                break;
            case ActivityType.condition:
                me.ClearModel.startPointX = -StyleDefine.activity.condition.diamondWidth - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.condition.diamondHeight - me.ClearModel.offset;
                me.ClearModel.width = 2 * StyleDefine.activity.condition.diamondWidth;
                me.ClearModel.heigth = 2 * StyleDefine.activity.condition.diamondHeight;
                break;
            case ActivityType.end:
                me.ClearModel.startPointX = -StyleDefine.activity.end.Radius - me.ClearModel.offset;
                me.ClearModel.startPointY = -StyleDefine.activity.end.Radius - me.ClearModel.offset;
                me.ClearModel.width = me.ClearModel.heigth = 2 * StyleDefine.activity.end.Radius;
                break;
        }
        me.ClearModel.startPointX -= 10;
        me.ClearModel.startPointY -= 10;
        me.ClearModel.width += 20;
        me.ClearModel.heigth += 20;

    },
    //清除图形
    /*清除画布上InitialClearModel中定义的范围*/
    clearActivity: function () {
        var me = this;
        var cxt = me.Picture;
        cxt.clearRect(me.ClearModel.startPointX, me.ClearModel.startPointY, me.ClearModel.width + me.ClearModel.offset * 2, me.ClearModel.heigth + me.ClearModel.offset * 2);
        if (me.captureX != null && me.captureX.iscapture)
            cxt.clearRect(me.captureX.point.X - me.ClearModel.width / 2 - me.ClearModel.offset - StyleDefine.activity.capturelength,
                0,
                me.ClearModel.width + 2 * me.ClearModel.offset + 2 * StyleDefine.activity.capturelength,
                StyleDefine.window.height);
        if (me.captureY != null && me.captureY.iscapture)
            cxt.clearRect(0,
                me.captureY.point.Y - me.ClearModel.heigth / 2 - me.ClearModel.offset - StyleDefine.activity.capturelength,
                StyleDefine.window.width,
                me.ClearModel.heigth + 2 * me.ClearModel.offset + 2 * StyleDefine.activity.capturelength);
        cxt.beginPath();
    },

    //绘制自由节点
    /*自由节点在流程图中用一个空心的圆圈表示
     r：圆圈的半径
     */
    DrawFreedom: function (r) {
        var me = this;
        var ctx = me.Picture;
        ctx.beginPath();
        ctx.arc(0, 0, r, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.stroke();
    },

    //设定节点的背景色
    /*tmp：指定的默认值
     y:节点高度/2
     */
    generateBackground: function (tmp, y) {
        var me = this;
        var fillStyle;

        if (tmp == undefined) {
            switch (me.isSelect) {

                case 0:
                    fillStyle = 'rgba(255,255,255,1)';
                    break;
                case 1:
                    var grd = me.Picture.createLinearGradient(0, -y, 0, y);
                    grd.addColorStop(0, "#e2eaf5");
                    grd.addColorStop(0.1, "#d9e6f8");
                    grd.addColorStop(0.1, "#cbdff7");
                    grd.addColorStop(0.21, "#daf2fd");
                    grd.addColorStop(0.21, "#bfdbff");
                    grd.addColorStop(0.21, "#b0cff7");
                    grd.addColorStop(0.1, "#dbe8f9");
                    grd.addColorStop(0.2, "#bfdbff");
                    grd.addColorStop(1, "#bfdbff");
                    fillStyle = grd;
                    break;
                case 2:
                    var grd = me.Picture.createLinearGradient(0, -y, 0, y);
                    grd.addColorStop(0, "#e2eaf5");
                    grd.addColorStop(0.1, "#d9e6f8");
                    grd.addColorStop(0.1, "#cbdff7");
                    grd.addColorStop(0.21, "#daf2fd");
                    grd.addColorStop(0.21, "#bfdbff");
                    grd.addColorStop(0.21, "#b0cff7");
                    grd.addColorStop(0.1, "#dbe8f9");
                    grd.addColorStop(0.2, "#bfdbff");
                    grd.addColorStop(1, "#bfdbff");
                    fillStyle = grd;
                    break;
                case 3:
                    var grd = me.Picture.createLinearGradient(0, -y, 0, y);
                    grd.addColorStop(0, "#fdcc91");
                    grd.addColorStop(0.5, "#fdb967");
                    grd.addColorStop(1, "#fbf76a");
                    fillStyle = grd;
                    break;

            }
        }
        else fillStyle = tmp;

        return fillStyle;

    },

    //绘制菱形
    /*分支节点、合并节点、条件节点用菱形表示，当绘制这几种图形时，调用此方法
     cxt：绘图对象
     position：中心位置
     strokeStyle：边线样式
     fillStyle：填充样式
     width：中心点到节点的距离
     height：中心点到节点的距离
     img：未用。。。。。。。
     */
    DrawDiamond: function (cxt, position, strokeStyle, fillStyle, width, height, img) {
        var me = this;
        me.DrawRuleStart();
        cxt.beginPath();
        cxt.save();
        cxt.shadowColor = "rgba(180,180,180,90)";
        //cxt.shadowOffsetX = 4;
        //cxt.shadowOffsetY = 4;
        //cxt.shadowBlur = 3;
        cxt.moveTo(-width, 0);
        cxt.lineTo(0, -height);
        cxt.lineTo(width, 0);
        cxt.lineTo(0, height);
        cxt.closePath();

        cxt.fillStyle = me.generateBackground(undefined, height);


        cxt.shadowOffsetX = 1;
        cxt.shadowOffsetY = 1;
        cxt.shadowBlur = 10;


        cxt.fill();
        cxt.restore();
        if (me.isDrawRuleStart)
            me.DrawRuleStart();
        if (me.activityType == ActivityType.merging || me.activityType == ActivityType.branching) {
            cxt.moveTo(-width + 5, 0);
            cxt.lineTo(width - 5, 0);
            if (me.activityType == ActivityType.branching) {
                cxt.moveTo(0, -height + 5);
                cxt.lineTo(0, height - 5);
            }
        }
        else if (me.activityType == ActivityType.condition) {
            if (fillStyle == null) fillStyle = 'rgba(0,0,0,1)';
            cxt.fillStyle = fillStyle;
            cxt.textAlign = "center";
            cxt.textBaseline = "middle";
            cxt.font = " 14px Microsoft YaHei";
            cxt.fillText(me.ActivityName, 0, 0);
        }
        cxt.stroke();

    },


    //绘制矩形
    /*起草节点、人工活动 使用矩形作为 表示图元
     cxt：绘图对象
     position：中心位置
     strokeStyle：边线样式
     fillStyle：填充样式
     width：中心点到节点的距离
     height：中心点到节点的距离
     img：未用。。。。。。。
     */
    DrawRect: function (cxt, position, vertexX, vertexY, width, height, angle, imgWidth, imgHeight, strokeStyle, fillStyle, img) {
        var me = this;
        var rect = cxt.roundRect(-vertexX, -vertexY, width, height, angle, true);
        cxt.fillStyle = me.generateBackground(undefined, height);
        rect.fill();
        cxt.restore();
        if (me.isDrawRuleStart)
            me.DrawRuleStart();
        var init = -vertexX + 25;
        var step = 15;
        cxt.fillStyle = fillStyle;
        cxt.font = " 14px Microsoft YaHei";
        cxt.textAlign = "center";
        cxt.textBaseline = "middle";
        var i = 0;
        var size = cxt.measureText(me.ActivityName);
        //一行
        if (size.width < 2 * vertexX - 10) {
            cxt.fillText(me.ActivityName, 0, 0);
        }
        //两行
        else if (size.width < 4 * vertexX - 20) {
            while (cxt.measureText(me.ActivityName.substring(0, i)).width <= size.width / 2) {
                ++i;
            }
            cxt.fillText(me.ActivityName.substring(0, i - 1), 0, -8);
            cxt.fillText(me.ActivityName.substring(i - 1, me.ActivityName.length), 0, 8);

        }//缩小文字间距
        else {
            while (cxt.measureText(me.ActivityName.substring(0, i)).width <= size.width / 2) {
                ++i;
            }
            cxt.fillText(me.ActivityName.substring(0, i - 1), 0, -8);
            cxt.fillText(me.ActivityName.substring(i - 1, me.ActivityName.length), 0, 8);
        }

        rect = cxt.roundRect(-vertexX, -vertexY, width, height, angle);
        rect.strokeStyle = strokeStyle;
        rect.stroke();

    },

    DrawStatus: function (status, coordinate, vertexY) {

        var cxt = this.Picture;
        var fillStyle = status == 1 ? '#00ff00' : '#ff0000';
        cxt.DrawCircle(coordinate, vertexY / 2, 5, fillStyle, false);

    },

    DrawCircle: function (cxt, r, style) {
        cxt.DrawCircle(0, 0, r, style, undefined, true);
    },

    ChangeSelectStatus: function (e) {
        if (this.status != this.isSelect || this.isDrawRuleStart != this.isDrawRule) {
            this.status = this.isSelect;
            this.isDrawRule = this.isDrawRuleStart
            this.ResetActivity();
            if (this.isSelect < 2)
                this.Canvas.css("z-index", "0");
        }
    },

    MoveActivity: function (e, istrans) {
        if (istrans == undefined)
            e = wf.mathHelper.Move(this.startMovePoint, this.currentActivityPosition, e);
        this.position = e;
        this.Draw(e, "rgba(0,0,0,1)", "rgba(0,0,0,1)");
        $.each(this.FromRule, function (i, val) {
            val.ReSetStartPoint(e);
        });
        $.each(this.ToRule, function (i, val) {
            val.ReSetEndPoint(e);
        });
    },

    SelectActivity: function (e, distinct) {

        var me = this;
        var tmpPoint = wf.canvasHelper.GetPoint(e);
        me.Canvas.css("z-index", "50");
        //设置当前操作节点
        wf.currentActivity = me;
        //设置当前节点样式
        me.ChangeSelectStatus(2, tmpPoint);
        //鼠标位置距离中心的距离，如果小于10，则更改当前选择操作为增加规则，否则仅仅选中当前节点
        if (me.CanHaveFromRule() && me.activityType != ActivityType.end && distinct < 10) {
            wf.gcommand = Command.addrules;
            var canInfo = wf.canvasHelper.InitialCanvas();
            var rule = new Rule(me);
            wf.currentRule = rule;
        }
        else {
            wf.gcommand = Command.selectactivity;
            wf.moveActivity = true;
            this.startMovePoint = tmpPoint;
            this.currentActivityPosition = me.position;
            if (this.activityType == ActivityType.branching) {
                this.MergingControl.ChangeSelectStatus(2, tmpPoint);
            }
            else if (this.activityType == ActivityType.merging) {
                this.BranchingControl.ChangeSelectStatus(2, tmpPoint);
            }
            wf.workspace.css("cursor", "move");
        }
    },

    ResetActivity: function () {
        var style = "rgba(0,0,0,1)";
        this.Draw(this.position, style, style);
    },

    DrawRuleStart: function () {
        if (this.activityType != ActivityType.start && this.activityType != ActivityType.end)
            this.DrawCircle(this.Picture, StyleDefine.Rule.SelectRadius, 'rgba(225,0,0,0.5)');
    },

    AddFromRule: function (rule) {
        this.FromRule[this.FromRule.length] = rule;
    },

    AddToRule: function (rule) {
        this.ToRule[this.ToRule.length] = rule;
    },

    CanHaveFromRule: function () {
        if (this.activityType == ActivityType.condition || this.activityType == ActivityType.branching || this.activityType == ActivityType.merging)
            return true;
        else if (this.activityType == ActivityType.end || this.activityType == ActivityType.freedom) return false;
        else {
            if (this.FromRule.length == 0) return true;
            else {
                var tmp = true;
                $.each(this.FromRule, function (i, val) {
                    if (val.endActivity.activityType != ActivityType.freedom) {
                        tmp = false;
                        return false;
                    }
                });
                return tmp;
            }
        }
    },

    CanHaveToRule: function () {
        var tmpAc = wf.currentRule.startActivity;
        var tmpFlag = true;
        for (m = 0; m < tmpAc.FromRule.length; m++)
            if (tmpAc.FromRule[m].endActivity.guid == this.guid)
                tmpFlag = false;
        return tmpFlag && this.activityType != ActivityType.start;
    },

    DrawFocus: function (point) {
        var cxt = this.Picture;
        cxt.beginPath();
        cxt.setTransform(1, 0, 0, 1, point.X, point.Y);
        cxt.strokeStyle = "rgba(225,0,0,1)";
        cxt.moveTo(-5, -5);
        cxt.lineTo(5, 5);
        cxt.moveTo(5, -5);
        cxt.lineTo(-5, 5);
        cxt.stroke();
    },

    DrawReferenceLine: function (currentPosition) {
        var me = this;
        var captureX = wf.canvasHelper.GetCaptureActivity('IsCaptureX', me.position, me);
        var captureY = wf.canvasHelper.GetCaptureActivity('IsCaptureY', me.position, me);
        var xd = false;
        var yd = false;
        this.captureX = captureX;
        this.captureY = captureY;
        var cxt = me.Picture;
        cxt.beginPath();
        if (captureX != null && captureX.iscapture) {
            cxt.DrawLine(new Point(captureX.point.X, 0), new Point(captureX.point.X, StyleDefine.window.height), StyleDefine.activity.referenceLineStyle);
            wf.canvasHelper.DrawFocusInvoke(me.Picture, captureX.activity);
            xd = true;
        }
        if (captureY != null && captureY.iscapture) {
            cxt.DrawLine(new Point(0, captureY.point.Y), new Point(StyleDefine.window.width, captureY.point.Y), StyleDefine.activity.referenceLineStyle);
            wf.canvasHelper.DrawFocusInvoke(me.Picture, captureY.activity);
            yd = true;
        }

        //存在交叉点,在交叉点出绘制
        if (xd || yd) {
            var point;
            if (xd && yd) {
                point = new Point(captureX.point.X, captureY.point.Y);
                wf.canvasHelper.DrawMovePoint(me.Picture, point, StyleDefine.activity.capturelength, StyleDefine.activity.referenceLineStyle);
            }
            else if (xd) {
                point = new Point(captureX.point.X, me.position.Y);
                wf.canvasHelper.DrawMovePoint(me.Picture, point, StyleDefine.activity.capturelength, StyleDefine.activity.referenceLineStyle);
            }
            else if (yd) {
                point = new Point(me.position.X, captureY.point.Y);
                wf.canvasHelper.DrawMovePoint(me.Picture, point, StyleDefine.activity.capturelength, StyleDefine.activity.referenceLineStyle);
            }
            this.capture = {
                'iscapture': true,
                'point': point
            }
        }
        else {
            this.capture.iscapture = false;
        }
    },
    GetActivityTypeName: function () {
        for (var i in ActivityType) {
            if (ActivityType[i] == this.activityType)
                return i;
        }
        return "Start"

    },
    //显示当前节点的属性窗口
    ShowProperty: function () {
        var that = this;
        var property = Property.InitailProperty(that);
        property.modal('show');
        $("#btnActivityPropOK").unbind().click(function () {
            Property.SaveData(that);
            property.modal('hide');
        });
    },
    //释放当前节点
    /*
     force  是否强制注销，默认值undefined
     */
    Dispose: function (force) {
        var me = this;
        if (me && (force != undefined || (this.activityType != ActivityType.start && this.activityType != ActivityType.end && this.activityType != ActivityType.drafting))) {
            this.Canvas.remove();
            this.Canvas = null;
            wf.activityHelper.Activitys.Remove(this);
            for (j = this.FromRule.length - 1; j >= 0; j--) {
                this.FromRule[j].Dispose(force);
            }
            for (j = this.ToRule.length - 1; j >= 0; j--) {
                this.ToRule[j].Dispose(force);
            }
            if (force == undefined) {
                if (this.activityType == ActivityType.branching) {

                    this.MergingControl.Dispose('1');
                }
                else if (this.activityType == ActivityType.merging) {
                    this.BranchingControl.Dispose('1');
                }
            }
            me = undefined;
        } else {
            window.alert("此活动不能删除");
        }
    },
    //保存数据时验证节点设计的是否有问题
    /*
     draftingActivity 起草节点
     endActivity  结束节点
     */
    Validate: function (draftingActivity, endActivity) {
        var me = this;
        if (me.activityType == ActivityType.start || me.activityType == ActivityType.end)
            return {
                result: true,
                message: ''
            };
        var result = me.PreValidate(wf.activityHelper.DraftingActivity);
        if (result.result) {
            result = me.AfterValidate(wf.activityHelper.EndActivity.Preactivity);
            if (result.result) {
                if (me.activityType == ActivityType.approval || me.activityType == ActivityType.drafting) {
                    if (me.ActivityProperty.activityParticipants == undefined || me.ActivityProperty.activityParticipants.length == 0) {
                        result.result = false;
                        result.errorMessage = "[" + this.ActivityProperty.activityName + "]-->必须选人\r\n";
                    }
                }
            }
        }
        return result;
    },
    //验证当前节点是否有到开始节点的路径
    /*draftingActivity起草节点*/
    PreValidate: function (draftingActivity) {

        var me = this;
        if (me.guid == draftingActivity.guid)
            return {
                result: true,
                errorMessage: ''
            };
        var flag = true;
        var errorMessage = "";
        if (this.ToRule.length == 0) {
            errorMessage = "[" + me.ActivityProperty.activityName + "]-->无前驱节点\r\n";
            flag = false;
        }
        if (flag) {
            //  me.GetReturnActivitys(true, me.guid);
            if (me.Preactivity == undefined || !me.Preactivity.contains(draftingActivity)) {
                errorMessage = "[" + this.ActivityProperty.activityName + "]-->无法进入节点\r\n";
                flag = false;
            }
        }
        return {
            result: flag,
            errorMessage: errorMessage
        };
    },

    //验证当前节点是否有到结束节点的路径
    /*endActivity结束节点*/
    AfterValidate: function (endActivity) {
        var flag = true;
        var me = this;
        var errorMessage = '';
        if (me.activityType == ActivityType.freedom)
            return {
                result: flag,
                errorMessage: errorMessage
            };
        if (me.FromRule.length == 0 && me.activityType != ActivityType.freedom && me.activityType != ActivityType.subprocesses) {
            errorMessage = "[" + this.ActivityProperty.activityName + "]-->无后继节点\r\n";
            flag = false;
        }
        else if (!endActivity.contains(this)) {

            errorMessage = "[" + this.ActivityProperty.activityName + "]-->无法结束节点\r\n";
            flag = false;
        }
        return {
            result: flag,
            errorMessage: errorMessage
        };
    }
}
var Rule = function (startActivity) {
    var canInfo = wf.canvasHelper.InitialCanvas();
    this.guid = Guid.NewGuid();
    this.RuleProperty = {};
    this.RuleProperty.guid = this.guid;
    this.RuleProperty.ruleType = 0;
    this.RuleProperty.isDel = 0;
    this.RuleProperty.lineType = 0
    this.Points = new Array();
    this.startActivity = startActivity;
    this.endActivity = null;
    this.Canvas = canInfo.canvas;
    this.Picture = canInfo.cxt;
    this.isSelect = false;
    this.vextPosition = -1;
    this.capture = {
        iscapture: false,
        point: new Point(0, 0)
    }
}
Rule.prototype = {
    ChangeID: function () {
        var me = this;
        me.guid = Guid.NewGuid();
        me.RuleProperty.guid = me.guid;
    },

    SetProperty: function (property) {
        this.RuleProperty = property;
        if (property.guid != undefined) {
            this.guid = property.guid
            this.DrawRuleName('rgba(0,0,0,1)');
        }
    },

    DrawRule: function (currentPosition) {
        var me = this;
        var point;
        if (me.Points.length == 0) {
            point = wf.currentRule.GetIntersectionPoint(me.startActivity, currentPosition);
        }
        else {
            point = me.Points[0];
        }
        var cxt = me.Picture;
        cxt.strokeStyle = 'rgba(0,0,0,1)';
        this.restore();
        cxt.moveTo(point.X, point.Y);
        for (i = 1; i < me.Points.length; i++)
            cxt.lineTo(me.Points[i].X, me.Points[i].Y);
        cxt.lineTo(currentPosition.X, currentPosition.Y);
        var arrow = Arrow(me.Points.length == 0 ? point : me.Points[me.Points.length - 1], currentPosition);
        cxt.lineTo(arrow.upArrow.X, arrow.upArrow.Y);
        cxt.moveTo(currentPosition.X, currentPosition.Y);
        cxt.lineTo(arrow.downArrow.X, arrow.downArrow.Y);
        cxt.stroke();

    },
    generateBackground: function (tmp) {
        var me = this;
        var fillStyle;
        if (tmp == undefined) {
            fillStyle = 'rgba(0,0,0,1)';
        }
        else fillStyle = tmp;
        return fillStyle;
    },
    //重置路径
    restore: function () {
        var cxt = this.Picture;
        cxt.clearRect(-100, -100, StyleDefine.window.width + 100, StyleDefine.window.height + 100);
        cxt.restore();
        cxt.beginPath();
    },
    ResetRule: function () {
        var me = this;
        var style = "rgba(0,0,0,1)";
        if (this.isSelect)
            style = "rgba(255,0,0,1)";
        style = me.generateBackground(style);
        this.Draw(style);
        if (this.isSelect)
            this.DrawCircle();
    },

    Draw: function (strokeStyle) {
        var me = this;
        var point = me.Points[0];
        var cxt = me.Picture;
        me.restore();
        cxt.strokeStyle = strokeStyle;
        cxt.moveTo(point.X, point.Y);
        for (i = 1; i < me.Points.length; i++)
            cxt.lineTo(me.Points[i].X, me.Points[i].Y);
        var arrow = Arrow(me.Points[me.Points.length - 2], me.Points[me.Points.length - 1]);
        cxt.lineTo(arrow.upArrow.X, arrow.upArrow.Y);
        cxt.moveTo(me.Points[me.Points.length - 1].X, me.Points[me.Points.length - 1].Y);
        cxt.lineTo(arrow.downArrow.X, arrow.downArrow.Y);
        cxt.stroke();
        me.DrawRuleName(strokeStyle);
    },

    ChangeSelectStatus: function () {
        var me = this;
        if (me.status != me.isSelect) {
            me.status = me.isSelect;
            this.ResetRule();
        }
    },

    nulloperation: function () {
    },

    ReSetStartPoint: function (currentPosition) {
        var me = this;
        if (me.Points.length > 2) {
            var flag1 = me.IsHorizontal(me.Points[0], me.Points[1]) && me.IsVertical(me.Points[1], me.Points[2]);
            var flag2 = me.IsVertical(me.Points[0], me.Points[1]) && me.IsHorizontal(me.Points[2], me.Points[1]);
            if (flag1 || flag2) {

            }
            else {
                me.nulloperation();
            }
            if (flag1) {
                me.Points[1].Y = currentPosition.Y;
            }
            if (flag2) {
                me.Points[1].X = currentPosition.X;
            }
            if (me.Points.length == 3) {
                var pointE = me.GetIntersectionPoint(me.endActivity, me.Points[1]);
                var pointS = me.GetIntersectionPoint(me.startActivity, me.Points[1]);
                me.Points[0] = pointS;
                me.Points[2] = pointE;
            }
            me.Points[0] = me.GetIntersectionPoint(me.startActivity, me.Points[1]);
        }
        else {
            var pointE = me.GetIntersectionPoint(me.endActivity, me.startActivity.position);
            var pointS = me.GetIntersectionPoint(me.startActivity, pointE);
            me.Points[0] = pointS;
            me.Points[1] = pointE;
        }
        me.ResetRule();
    },

    ReSetEndPoint: function (currentPosition) {
        var me = this;
        if (me.Points.length > 2) {
            if (me.IsHorizontal(me.Points[me.Points.length - 1], me.Points[me.Points.length - 2])
                && me.IsVertical(me.Points[me.Points.length - 2], me.Points[me.Points.length - 3])
            ) {
                me.Points[me.Points.length - 2].Y = currentPosition.Y;
            }
            if (me.IsVertical(me.Points[me.Points.length - 1], me.Points[me.Points.length - 2]) &&
                me.IsHorizontal(me.Points[me.Points.length - 2], me.Points[me.Points.length - 3])) {
                me.Points[me.Points.length - 2].X = currentPosition.X;
            }
            if (me.Points.length == 3) {
                var pointE = me.GetIntersectionPoint(me.endActivity, me.Points[1]);
                var pointS = me.GetIntersectionPoint(me.startActivity, me.Points[1]);
                me.Points[0] = pointS;
                me.Points[2] = pointE;
            }
            else
                me.Points[me.Points.length - 1] = me.GetIntersectionPoint(me.endActivity, me.Points[me.Points.length - 2]);
        }
        else {
            var pointE = me.GetIntersectionPoint(me.endActivity, me.startActivity.position);
            var pointS = me.GetIntersectionPoint(me.startActivity, pointE);
            me.Points[0] = pointS;
            me.Points[1] = pointE;
        }
        me.ResetRule();
    },
    IsHorizontal: function (p1, p2) {
        if (Math.abs(p1.Y - p2.Y) < 2)
            return true;
        return false;
    },

    IsVertical: function (p1, p2) {
        if (Math.abs(p1.X - p2.X) < 2)
            return true;
        return false;
    },
    ResetPoint: function (e) {
        var me = this;
        var point = wf.canvasHelper.GetPoint(e);
        if (me.pointPosition != -1) {
            var ishandler = false;
            if (me.Points.length > 3) {
                if (me.vextPosition > 0 && me.vextPosition < me.Points.length - 1) {
                    if (me.vextPosition < me.Points.length - 2) {
                        if (me.IsHorizontal(me.Points[me.vextPosition - 1], me.Points[me.vextPosition]) && me.IsHorizontal(me.Points[me.vextPosition + 1], me.Points[me.vextPosition + 2])) {
                            me.Points[me.vextPosition].X = point.X;
                            me.Points[me.vextPosition + 1].X = point.X;
                            //me.SetStartEndPoint(point);
                            ishandler = true;
                        }
                        else if (me.IsVertical(me.Points[me.vextPosition - 1], me.Points[me.vextPosition]) && me.IsVertical(me.Points[me.vextPosition + 1], me.Points[me.vextPosition + 2])) {
                            me.Points[me.vextPosition].Y = point.Y;
                            me.Points[me.vextPosition + 1].Y = point.Y;
                            //me.SetStartEndPoint(point);
                            ishandler = true;
                        }
                    }
                    else if (me.vextPosition > 1) {
                        if (me.IsHorizontal(me.Points[me.vextPosition + 1], me.Points[me.vextPosition]) && me.IsHorizontal(me.Points[me.vextPosition - 1], me.Points[me.vextPosition - 2])) {
                            me.Points[me.vextPosition].X = point.X;
                            me.Points[me.vextPosition - 1].X = point.X;
                            //me.SetStartEndPoint(point);
                            ishandler = true;
                        }
                        else if (me.IsVertical(me.Points[me.vextPosition + 1], me.Points[me.vextPosition]) && me.IsVertical(me.Points[me.vextPosition - 1], me.Points[me.vextPosition - 2])) {
                            me.Points[me.vextPosition].Y = point.Y;
                            me.Points[me.vextPosition - 1].Y = point.Y;
                            //me.SetStartEndPoint(point);
                            ishandler = true;
                        }
                    }
                }
            }

            if (!ishandler) {
                me.Points[me.vextPosition] = point;
                me.SetStartEndPoint(point);
            }
            this.ResetRule();
            this.DrawCircle();
        }
    },
    SetStartEndPoint: function (point) {
        var me = this;
        if (me.vextPosition == 1) {
            me.Points[0] = me.GetIntersectionPoint(me.startActivity, point);
        }
        if (me.vextPosition == me.Points.length - 2) {
            me.Points[me.Points.length - 1] = me.GetIntersectionPoint(me.endActivity, point);
        }
    },
    AddPoint: function (point) {
        var me = this;
        if (me.capture.iscapture)
            point = me.capture.point;
        if (me.Points.length == 0)
            me.Points[0] = me.GetIntersectionPoint(me.startActivity, point);
        me.Points[me.Points.length] = point;
    },
    DrawCircle: function () {
        var rule = this;
        var cxt = rule.Picture;
        rule.ChangeSelectStatus(true);
        for (i = 0; i < rule.Points.length; i++) {
            cxt.DrawCircle(rule.Points[i].X, rule.Points[i].Y, 5, 'rgba(225,0,0,0.5)');
        }
    },
    SelectRule: function (result) {
        this.DrawCircle();
        wf.gcommand = Command.selectrule;
        if (result.selectType == 1) {
            wf.moveRule = true;
            wf.workspace.css("cursor", "move");
        }
    },
    //判断当前规则是否被鼠标点中
    IsSelect: function (point) {
        var result = {
            'isSelect': false,
            'selectedObject': null,
            'distinct': 1000,
            'vextdistinct': 1000,
            'selectType': 0
        };
        for (i = 1; i < this.Points.length; i++) {
            var dis = wf.mathHelper.GetNearestDistance(this.Points[i - 1], this.Points[i], point);
            if (dis < result.distinct)
                result.distinct = dis;
            var vextdistinct = wf.mathHelper.PointDistinct(point.X, point.Y, this.Points[i].X, this.Points[i].Y);
            var position = i;
            if (i == 1) {
                var vextdistinct1 = wf.mathHelper.PointDistinct(point, this.Points[0]);
                if (vextdistinct1 < vextdistinct) {
                    vextdistinct = vextdistinct1;
                    position = 0;
                }
            }
            if (vextdistinct < result.vextdistinct) {
                result.vextdistinct = vextdistinct;
                this.vextPosition = position;
            }
        }
        if (result.distinct < 2 || result.vextdistinct < 5) {
            result.isSelect = true;
            result.selectedObject = this;
            result.selectType = result.vextdistinct < 5 ? 1 : 0;
        }
        return result;
    },

    ChangeActivity: function (point, result) {
        var me = this;
        if (me.vextPosition == me.Points.length - 1) {
            //更改endActivity
            if (result.isSelect) {
                me.endActivity.ToRule.Remove(this);
                me.endActivity = result.selectedObject;
                me.endActivity.ToRule[me.endActivity.ToRule.length] = this;
            }
            me.ReSetEndPoint(point);
        }
        else if (me.vextPosition == 0) {
            if (result.isSelect && result.selectedObject.CanHaveFromRule()) {

                me.startActivity.FromRule.Remove(this);
                me.startActivity = result.selectedObject;
                me.startActivity.FromRule[me.startActivity.FromRule.length] = this;
            }
            me.ReSetStartPoint(point);
        }
    },
    //获取所有线段中最长的一条
    DrawRuleName: function (strokeStyle) {
        var me = this;
        if (me.RuleProperty != undefined && me.RuleProperty.ruleName != undefined && me.RuleProperty.ruleName != '') {
            var tmp = 0;
            var dis = 0;
            var a = 0;
            while (a < me.Points.length - 1) {
                var tmpDis = wf.mathHelper.PointDistinct(me.Points[a], me.Points[++a]);
                if (tmpDis > dis) {
                    dis = tmpDis;
                    tmp = a;
                }
            }
            var p1;
            var p2;
            if (tmp > 0) {
                if (me.Points[tmp - 1].X > me.Points[tmp].X) {
                    p2 = me.Points[tmp - 1];
                    p1 = me.Points[tmp];
                }
                else {
                    p1 = me.Points[tmp - 1];
                    p2 = me.Points[tmp];
                }
                //文字旋转角度
                var angle;
                var sincos = wf.mathHelper.Angle(p1, p2);
                //0~180
                if (sincos.sin > 0) {
                    angle = Math.acos(sincos.cos);
                }
                //180~360
                else if (sincos.sin < 0) {
                    angle = 2 * Math.PI - Math.acos(sincos.cos);
                }
                else {
                    if (sincos.cos == 1) angle = 0;
                    else if (sincos.cos == -1) angle = Math.PI;
                }
                me.Picture.save();
                me.Picture.translate(p1.X + Math.cos(angle) * dis / 3 + 10 * +Math.sin(angle), p1.Y + Math.sin(angle) * dis / 3 - 10 * Math.cos(angle));
                me.Picture.rotate(angle);
                me.Picture.fillStyle = strokeStyle;
                me.Picture.fillText(me.RuleProperty.ruleName, 0, 0);
                me.Picture.restore();
            }
        }
    },

    GetIntersectionPoint: function (activity, point) {
        if (activity.activityType == ActivityType.start || activity.activityType == ActivityType.end || activity.activityType == ActivityType.freedom) {
            var r;
            if (activity.activityType == ActivityType.start) {
                r = StyleDefine.activity.start.Radius;
            }
            else if (activity.activityType == ActivityType.end) {
                r = StyleDefine.activity.end.Radius;
            }
            else if (activity.activityType == ActivityType.freedom) {
                r = StyleDefine.activity.end.Radius;
            }
            point = new Point(point.X - activity.position.X, point.Y - activity.position.Y);
            var dis = wf.mathHelper.PointDistinct(point.X, point.Y, 0, 0);
            var sin = point.X / dis;
            var cos = point.Y / dis;
            var resultX = r * sin + activity.position.X;
            var resultY = r * cos + activity.position.Y;
            return new Point(resultX, resultY);
        }
        else if (activity.activityType == ActivityType.condition || activity.activityType == ActivityType.merging || activity.activityType == ActivityType.branching) {
            var p1;
            var p2;
            var width;
            var height;
            if (activity.activityType == ActivityType.condition) {
                width = StyleDefine.activity.condition.diamondWidth;
                height = StyleDefine.activity.condition.diamondHeight;
            }
            else if (activity.activityType == ActivityType.merging) {
                width = StyleDefine.activity.merging.diamondWidth;
                height = StyleDefine.activity.merging.diamondHeight;
            }
            else if (activity.activityType == ActivityType.branching) {
                width = StyleDefine.activity.branching.diamondWidth;
                height = StyleDefine.activity.branching.diamondHeight;
            }
            if (point.X > activity.position.X) {
                //右侧偏下
                if (point.Y > activity.position.Y) {
                    p1 = new Point(0, height);
                    p2 = new Point(width, 0);
                }
                else if (point.Y == activity.position.Y) {
                    return new Point(activity.position.X + width, activity.position.Y)
                }
                //右侧偏上
                else {
                    p1 = new Point(0, -height);
                    p2 = new Point(width, 0);
                }
            }
            else if (point.X == activity.position.X) {
                if (point.Y > activity.position.Y)
                    return new Point(activity.position.X, activity.position.Y + height);
                else return new Point(activity.position.X, activity.position.Y - height);
            }
            else {
                //左侧偏上
                if (point.Y > activity.position.Y) {
                    p1 = new Point(-width, 0);
                    p2 = new Point(0, height);
                }
                else if (point.Y == activity.position.Y) {
                    return new Point(activity.position.X - width, activity.position.Y);
                }
                else {
                    p1 = new Point(-width, 0),
                        p2 = new Point(0, -height)
                }
            }
            return wf.mathHelper.GetIntersectionPoint(activity.position, point, p1, p2);
        }
        else {
            var activityRectVertexY;
            var activityRectVertexX;
            var r;
            if (activity.activityType == ActivityType.drafting) {
                activityRectVertexY = StyleDefine.activity.drafting.activityRectVertexY;
                activityRectVertexX = StyleDefine.activity.drafting.activityRectVertexX;
                r = StyleDefine.activity.drafting.activityRectAngle;
            }
            else if (activity.activityType == ActivityType.approval) {
                activityRectVertexY = StyleDefine.activity.approval.activityRectVertexY;
                activityRectVertexX = StyleDefine.activity.approval.activityRectVertexX;
                r = StyleDefine.activity.approval.activityRectAngle;
            }
            //以当前顶点为坐标系
            var relativeCoordinates = new Point(point.X - activity.position.X, point.Y - activity.position.Y);
            var me = this;
            var k = 0;
            if (relativeCoordinates.X != 0) {
                k = relativeCoordinates.Y / relativeCoordinates.X;
            }
            //鼠标在节点的右侧
            if (relativeCoordinates.X > 0) {
                //                    activityRectVertexX
                //                    activityRectVertexY
                //右侧偏下
                if (relativeCoordinates.Y > 0) {
                    var y1 = activityRectVertexY;
                    var x1 = y1 / k;
                    var result = new Point(x1, y1);
                    var center = new Point(activityRectVertexX - r, activityRectVertexY - r);
                    if (x1 > activityRectVertexX) {
                        //在弧上
                        result.X = activityRectVertexX;
                        result.Y = k * result.X;
                    }
                    if (result.X > center.X && result.Y > center.Y) {
                        var tmp = wf.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                        if (tmp != null)
                            result = tmp;
                    }
                    return result.MovePoint(activity.position);
                }
                else if (relativeCoordinates.Y == 0) {
                    return new Point(activity.position.X + activityRectVertexX, activity.position.Y);
                }
                //右侧偏上
                else {
                    var y1 = -activityRectVertexY;
                    var x1 = y1 / k;
                    var result = new Point(x1, y1);
                    var center = new Point(activityRectVertexX - r, -activityRectVertexY + r);
                    if (result.X > center.X) {
                        result.X = activityRectVertexX;
                        result.Y = k * result.X;
                    }
                    if (result.X > center.X && result.Y < center.Y) {
                        var tmp = wf.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                        if (tmp != null)
                            result = tmp;
                    }
                    return result.MovePoint(activity.position);
                }
            }
            else if (relativeCoordinates.X == 0) {
                if (relativeCoordinates.Y > 0) {
                    return new Point(activity.position.X, activity.position.Y + activityRectVertexY);
                }
                else {
                    return new Point(activity.position.X, activity.position.Y - activityRectVertexY);
                }
            }
            else {
                //左侧偏上
                if (relativeCoordinates.Y > 0) {
                    var y1 = activityRectVertexY;
                    var x1 = y1 / k;
                    var result = new Point(x1, y1);
                    var center = new Point(-activityRectVertexX + r, activityRectVertexY - r);
                    if (x1 < -activityRectVertexX) {
                        result.X = -activityRectVertexX;
                        result.Y = k * result.X;
                    }
                    if (result.X < center.X && result.Y > center.Y) {

                        var tmp = wf.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                        if (tmp != null)
                            result = tmp;
                    }
                    return result.MovePoint(activity.position);
                }
                else if (relativeCoordinates.Y == 0) {
                    return new Point(activity.position.X - activityRectVertexX, activity.position.Y);
                }
                else {
                    var y1 = -activityRectVertexY;
                    var x1 = y1 / k;
                    var result = new Point(x1, y1);
                    var center = new Point(-activityRectVertexX + r, -activityRectVertexY + r);
                    if (x1 < -activityRectVertexX) {
                        if (x1 < -activityRectVertexX + r) {
                            result.X = -activityRectVertexX;
                            result.Y = k * result.X;
                        }
                    }
                    if (result.X < center.X && result.Y < center.Y) {
                        var tmp = wf.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                        if (tmp != null) result = tmp;
                    }
                    return result.MovePoint(activity.position);
                }
            }
        }

    },

    //currentPosition,鼠标当前位置
    DrawReferenceLine: function (currentPosition) {
        var me = this;
        var count = 0;
        var point;
        if (me.Points.length == 0)
            point = me.startActivity.position;
        else point = me.Points[me.Points.length - 1];
        me.IsCapture(currentPosition, point)
        var xd = false;
        var yd = false;
        var captureX = wf.canvasHelper.GetCaptureActivity('IsCaptureX', currentPosition);
        var captureY = wf.canvasHelper.GetCaptureActivity('IsCaptureY', currentPosition);
        if (captureX != null && captureX.iscapture) {
            me.Picture.DrawLine(new Point(captureX.point.X, 0), new Point(captureX.point.X, StyleDefine.window.height), StyleDefine.activity.referenceLineStyle);
            wf.canvasHelper.DrawFocusInvoke(me.Picture, captureX.activity);
            if (this.capture.direct == 'y')
                xd = true;
        }
        if (captureY != null && captureY.iscapture) {
            me.Picture.DrawLine(new Point(0, captureY.point.Y), new Point(StyleDefine.window.width, captureY.point.Y), StyleDefine.activity.referenceLineStyle);
            wf.canvasHelper.DrawFocusInvoke(me.Picture, captureY.activity);
            if (this.capture.direct == 'x')
                yd = true;
        } //存在交叉点,在交叉点出绘制
        var point = null;
        if (this.capture.iscapture && xd)
            point = new Point(captureX.point.X, this.capture.point.Y);
        else if (this.capture.iscapture && yd)
            point = new Point(this.capture.point.X, captureY.point.Y);
        else if (this.capture.iscapture)
            point = this.capture.point;
        else if (xd)
            point = captureX.point;
        else if (yd)
            point = captureY.point;
        if (point != null) {
            this.capture.iscapture = true;
            this.capture.point = point;
            this.DrawMovePoint(point);
        }
    },
    //currentPosition当前位置
    //point参考点
    IsCapture: function (currentPosition, point) {
        var cxt = this.Picture;
        cxt.strokeStyle = StyleDefine.Rule.referenceLineStyle;
        cxt.restore();
        cxt.beginPath();

        this.capture = {
            'iscapture': false,
            'point': null,
            'direct': null
        }

        if (wf.mathHelper.PointDistinct(currentPosition, new Point(point.X, currentPosition.Y)) < 10) {
            cxt.moveTo(point.X, 0);
            cxt.lineTo(point.X, StyleDefine.window.height);
            this.capture = {
                'iscapture': true,
                'point': new Point(point.X, currentPosition.Y),
                'direct': 'x'
            }
            cxt.stroke();
        }
        else if (wf.mathHelper.PointDistinct(currentPosition, new Point(currentPosition.X, point.Y)) < 10) {
            cxt.moveTo(0, point.Y);
            cxt.lineTo(StyleDefine.window.width, point.Y);
            this.capture = {
                'iscapture': true,
                'point': new Point(currentPosition.X, point.Y),
                'direct': 'y'
            }
            cxt.stroke();
        }
        return this.capture;
    },

    DrawMovePoint: function (point) {
        var x1 = point.X - StyleDefine.rule.capturelength;
        var y1 = point.Y - StyleDefine.rule.capturelength;
        var cxt = this.Picture;
        cxt.strokeStyle = StyleDefine.rule.strokeStyle;
        cxt.beginPath();
        cxt.rect(x1, y1, 2 * StyleDefine.rule.capturelength, 2 * StyleDefine.rule.capturelength);
        cxt.stroke();
    },
    ShowProperty: function () {
        var that=this;
        var property = $('#ruleProperty');
        property.modal();
        ruleProperty.InitialPage($('#ruleProperty .widget-main'), that);
        $("#btnRulePropOK").click(function () {
            ruleProperty.SaveData(that);
            property.modal('hide');
        });
    },
    Dispose: function (force) {
        var me = this;
        if (force != undefined || me.startActivity.activityType != ActivityType.start) {
            me.startActivity.FromRule.Remove(this);
            if (me.endActivity != undefined)
                me.endActivity.ToRule.Remove(this);
            me.Canvas.remove();
            me.Canvas = null;
            wf.rules.Remove(me);
        }
        else {
            window.alert("此规则不能删除");
        }
    },
    Validate: function () {
    }
}
/*
 Property
 */
var BaseProperty = {
    ActivityProperty: {
        activityName: {
            'id': 'activityName',
            'name': 'activityName',
            'title': "节点名称",
        },
        description: {
            'id': 'description',
            'name': 'description',
            'title': "描述",
        },
        FINISH_TYPE: {
            'id': 'FINISH_TYPE',
            'name': 'FINISH_TYPE',
            'title': "完成方式",
            'array': [['0', '单一'], ['1', '百分比'], ['2', '数量'], ['3', '全部']]
        },
        finishNumber: {
            'id': 'finishNumber',
            'name': 'finishNumber',
            'title': "完成数量"
        },
        IS_AUTOMATIC: {
            'id': 'IS_AUTOMATIC',
            'name': 'IS_AUTOMATIC',
            'title': "选人方式",
            'array': [['0', '手工选人'], ['1', '自动选人']]
        },
        IS_UPLOAD_AUTOMATIC: {
            'id': 'IS_UPLOAD_AUTOMATIC',
            'name': 'IS_UPLOAD_AUTOMATIC',
            'title': "限制上传附件"
        },
        ENABLE_ATTACHMENT: {
            'id': 'ENABLE_ATTACHMENT',
            'name': 'ENABLE_ATTACHMENT',
            'title': "上传附件"
        },
        OPEN_MODE_TYPE: {
            'id': 'OPEN_MODE_TYPE',
            'name': 'OPEN_MODE_TYPE',
            'title': "打开模式",
            'array': [['0', '强制保留痕迹'], ['1', '核稿模式'], ['2', '普通编辑模式'], ['3', '只读模式'], ['4', '手写模式']]
        },
        //是否编辑表单
        ENABLE_EDIT_ATTACHMENT: {
            'id': 'ENABLE_EDIT_ATTACHMENT',
            'name': 'ENABLE_EDIT_ATTACHMENT',
            'title': "编辑表单"
        },
        ENABLE_ATTACHMENT: {
            'id': 'ENABLE_ATTACHMENT',
            'name': 'ENABLE_ATTACHMENT',
            'title': "上传附件"
        },
        //是否查看审批历史
        ENABLE_SHOW: {
            'id': 'ENABLE_SHOW',
            'name': 'ENABLE_SHOW',
            'title': "审批历史"
        },
        //是否提交意见
        ENABLE_SUGGESTION: {
            'id': 'ENABLE_SUGGESTION',
            'name': 'ENABLE_SUGGESTION',
            'title': "意见"
        },
        //是否终止流程
        ENABLE_TERMINATE_FLOW: {
            'id': 'ENABLE_TERMINATE_FLOW',
            'name': 'ENABLE_TERMINATE_FLOW',
            'title': "终止"
        },
        //是否需要签名
        ENABLE_SIGNATURE: {
            'id': 'ENABLE_SIGNATURE',
            'name': 'ENABLE_SIGNATURE',
            'title': "签名"
        },
        ENABLE_TRANSFER: {
            'id': 'ENABLE_TRANSFER',
            'name': 'ENABLE_TRANSFER',
            'title': "转批"
        },
        ENABLE_CIRCULATED: {
            'id': 'ENABLE_CIRCULATED',
            'name': 'ENABLE_CIRCULATED',
            'title': "传阅"
        },
        ENABLE_FILED: {
            'id': 'ENABLE_FILED',
            'name': 'ENABLE_FILED',
            'title': "归档"
        },
        IS_MERGR: {
            'id': 'IS_MERGR',
            'name': 'IS_MERGR',
            'title': "合并审批"
        }
    },
    InitialPage: function (parent, activity) {
        this.activity = activity;
        this.InitialControl(parent);
        this.InitialData(activity);
    },
    InitialData: function () {
        debugger;
        var me = this;
        this.ActivityProperty.activityName.control.val(this.activity.ActivityName);
        if (this.activity.ActivityProperty != undefined) {
            this.ActivityProperty.activityName.control.val(this.activity.ActivityProperty.activityName);
            this.ActivityProperty.description.control.val(this.activity.ActivityProperty.description);
            this.ActivityProperty.FINISH_TYPE.control.val(this.activity.ActivityProperty.FINISH_TYPE);
            this.ActivityProperty.finishNumber.control.val(this.activity.ActivityProperty.finishNumber);

            if (this.activity.ActivityProperty.FINISH_TYPE == 1 || this.activity.ActivityProperty.FINISH_TYPE == 2) {
                this.ActivityProperty.finishNumber.control.removeAttr("disabled");
            }
            else {
                this.ActivityProperty.finishNumber.control.attr("disabled", "disabled");
                this.ActivityProperty.finishNumber.control.val('');
            }
            this.ActivityProperty.IS_AUTOMATIC.control.val(this.activity.ActivityProperty.IS_AUTOMATIC);
            this.ActivityProperty.OPEN_MODE_TYPE.control.val(this.activity.ActivityProperty.OPEN_MODE_TYPE);
            if (this.activity.ActivityProperty.ENABLE_EDIT_ATTACHMENT == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_EDIT_ATTACHMENT.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_EDIT_ATTACHMENT.control);

            if (this.activity.ActivityProperty.ENABLE_ATTACHMENT == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_ATTACHMENT.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_ATTACHMENT.control);
            if (this.activity.ActivityProperty.IS_UPLOAD_AUTOMATIC == 1)
                this.SetCheck(this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control);
            else
                this.SetUnCheck(this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control);

            if (this.activity.ActivityProperty.ENABLE_SHOW == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_SHOW.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_SHOW.control)
            if (this.activity.ActivityProperty.ENABLE_SUGGESTION == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_SUGGESTION.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_SUGGESTION.control);
            //if (this.activity.ActivityProperty.ENABLE_TRANSIT == 1)
            //    this.SetCheck(this.ActivityProperty.ENABLE_TRANSIT.control);
            //else
            //    this.SetUnCheck(this.ActivityProperty.ENABLE_TRANSIT.control);
            if (this.activity.ActivityProperty.ENABLE_TERMINATE_FLOW == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_TERMINATE_FLOW.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_TERMINATE_FLOW.control);
            if (this.activity.ActivityProperty.ENABLE_SIGNATURE == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_SIGNATURE.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_SIGNATURE.control);
            if (this.activity.ActivityProperty.ENABLE_TRANSFER == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_TRANSFER.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_TRANSFER.control);
            if (this.activity.ActivityProperty.ENABLE_CIRCULATED == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_CIRCULATED.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_CIRCULATED.control);
            if (this.activity.ActivityProperty.ENABLE_FILED == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_FILED.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_FILED.control);
            if (this.activity.ActivityProperty.IS_MERGR == 1)
                this.SetCheck(this.ActivityProperty.IS_MERGR.control);
            else
                this.SetUnCheck(this.ActivityProperty.IS_MERGR.control);
        }
        else {
            this.ActivityProperty.description.control.val('');
            this.ActivityProperty.FINISH_TYPE.control.val(0);
            this.ActivityProperty.finishNumber.control.attr("disabled", "disabled");
            this.ActivityProperty.finishNumber.control.val('');
            this.ActivityProperty.IS_AUTOMATIC.control.val(0);
            this.ActivityProperty.OPEN_MODE_TYPE.control.val(0);
            this.ActivityProperty.ENABLE_EDIT_ATTACHMENT.control.attr("checked", false);
            this.ActivityProperty.ENABLE_ATTACHMENT.control.attr("checked", false);
            this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control.attr("checked", false);

            this.ActivityProperty.ENABLE_SHOW.control.attr("checked", false);
            this.ActivityProperty.ENABLE_SUGGESTION.control.attr("checked", false);
            //this.ActivityProperty.ENABLE_TRANSFER.control.attr("checked", false);
            this.ActivityProperty.ENABLE_TERMINATE_FLOW.control.attr("checked", false);
            this.ActivityProperty.ENABLE_SIGNATURE.control.attr("checked", false);
            this.ActivityProperty.ENABLE_TRANSFER.control.attr("checked", false);
            this.ActivityProperty.ENABLE_CIRCULATED.control.attr("checked", false);
            this.ActivityProperty.ENABLE_FILED.control.attr("checked", false);
            this.ActivityProperty.IS_MERGR.control.attr("checked", false);

        }
    },
    InitialControl: function (parent) {
        parent.empty();
        var activityType = this.activity.activityType;
        var form = $('<form class="form-horizontal" role="form">');
        parent.append(form);
        switch (activityType) {
            case ActivityType.start:
                start(form, this);
                break;
            case ActivityType.end:
                end(form, this);
                break;
            case ActivityType.drafting:
                drafting(form, this);
                break;
            case ActivityType.approval:
                approval(form, this);
                break;
            case ActivityType.condition:
                condition(form, this);
                break;
            case ActivityType.freedom:
                freedom(form, this);
                break;
        }
        function start(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            )
        }

        function end(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    checkbox(that.ActivityProperty.ENABLE_FILED, 2, 2)
                )
            )
        }

        function drafting(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                ).append(
                    select(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                ).append(
                    checkbox(that.ActivityProperty.IS_UPLOAD_AUTOMATIC, 2)
                )
            )
        }

        function approval(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.FINISH_TYPE, 2)
                ).append(
                    select(that.ActivityProperty.FINISH_TYPE, 2)
                ).append(
                    input(that.ActivityProperty.finishNumber, 2)
                ).append(
                    label(that.ActivityProperty.IS_AUTOMATIC, 2)
                ).append(
                    select(that.ActivityProperty.IS_AUTOMATIC, 2)
                ).append(
                    checkbox(that.ActivityProperty.IS_UPLOAD_AUTOMATIC, 2)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                ).append(
                    select(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                )
            ).append(
                $('<div class="form-group">').append(
                    checkbox(that.ActivityProperty.ENABLE_EDIT_ATTACHMENT, 2, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_ATTACHMENT, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_SHOW, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_SUGGESTION, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_TERMINATE_FLOW, 2)
                )
            ).append(
                $('<div class="form-group">').append(
                    checkbox(that.ActivityProperty.ENABLE_SIGNATURE, 2, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_TRANSFER, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_CIRCULATED, 2)
                ).append(
                    checkbox(that.ActivityProperty.IS_MERGR, 2)
                )
            )
        }

        function condition(form, that) {

        }

        function freedom(form, that) {

        }

        function label(data, column, offset) {
            var result = $($.format('<label class="col-sm-{0} col-sm-offset-{1} control-label no-padding-right">', column, offset == undefined ? 0 : offset)).html(data.title)
                .attr('class', 'col-sm-2 control-label no-padding-right').attr('for', data.name)
            return result;
        }

        function input(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                data.control = $('<input class="form-control" type="text">').attr('id', data.id).attr('name', data.name).attr('placeholder', data.title)
            )
            return result;
        }

        function checkbox(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                $('<div class="checkbox">').append(
                    $('<label>').append(
                        data.control = $('<input class="colored-success" type="checkbox">').attr('id', data.id).attr('name', data.name)
                    ).append(
                        $('<span class="text">').html(data.title)
                    )
                )
            )
            return result;
        }

        function select(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                option(data)
            )
            return result;
            function option(data) {
                data.control = $('<select >').attr('id', data.id).attr('name', data.name)
                $.each(data.array, function (i, val) {
                    data.control.append($('<option>').attr('value', val[0]).html(val[1]));
                })
                return data.control;
            }
        }
    },
    SaveData: function (activity) {
        if (activity.ActivityProperty == undefined) {
            activity.ActivityProperty = {};
        }
        activity.ActivityProperty.activityName = this.ActivityProperty.activityName.control == undefined ? '' : this.ActivityProperty.activityName.control.val();
        activity.ActivityProperty.description = this.ActivityProperty.description.control == undefined ? '' : this.ActivityProperty.description.control.val();
        activity.ActivityProperty.FINISH_TYPE = this.ActivityProperty.FINISH_TYPE.control == undefined ? '' : this.ActivityProperty.FINISH_TYPE.control.find("option:selected").val();
        activity.ActivityProperty.finishNumber = this.ActivityProperty.finishNumber.control == undefined ? '' : this.ActivityProperty.finishNumber.control.val();
        activity.ActivityProperty.IS_AUTOMATIC = this.ActivityProperty.IS_AUTOMATIC.control == undefined ? '' : this.ActivityProperty.IS_AUTOMATIC.control.find("option:selected").val();
        activity.ActivityProperty.OPEN_MODE_TYPE = this.ActivityProperty.OPEN_MODE_TYPE.control == undefined ? '' : this.ActivityProperty.OPEN_MODE_TYPE.control.find("option:selected").val();
        activity.ActivityProperty.ENABLE_ATTACHMENT = this.ActivityProperty.ENABLE_ATTACHMENT.control == undefined ? '' : this.ActivityProperty.ENABLE_ATTACHMENT.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.IS_UPLOAD_AUTOMATIC = this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control == undefined ? '' : this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_SHOW = this.ActivityProperty.ENABLE_SHOW.control == undefined ? '' : this.ActivityProperty.ENABLE_SHOW.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_SUGGESTION = this.ActivityProperty.ENABLE_SUGGESTION.control == undefined ? '' : this.ActivityProperty.ENABLE_SUGGESTION.control.is(":checked") ? 1 : 0;
        //activity.ActivityProperty.ENABLE_TRANSIT = this.ActivityProperty.ENABLE_TRANSFER.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_TERMINATE_FLOW = this.ActivityProperty.ENABLE_TERMINATE_FLOW.control == undefined ? '' : this.ActivityProperty.ENABLE_TERMINATE_FLOW.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_SIGNATURE = this.ActivityProperty.ENABLE_SIGNATURE.control == undefined ? '' : this.ActivityProperty.ENABLE_SIGNATURE.control.is(":checked") ? 1 : 0;
        activity.ActivityName = this.ActivityProperty.activityName.control == undefined ? '' : this.activity.ActivityProperty.activityName;
        activity.ActivityProperty.ENABLE_TRANSFER = this.ActivityProperty.ENABLE_TRANSFER.control == undefined ? '' : this.ActivityProperty.ENABLE_TRANSFER.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_CIRCULATED = this.ActivityProperty.ENABLE_CIRCULATED.control == undefined ? '' : this.ActivityProperty.ENABLE_CIRCULATED.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_FILED = this.ActivityProperty.ENABLE_FILED.control == undefined ? '' : this.ActivityProperty.ENABLE_FILED.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.status = 0;
        for (i in ActivityPropertyStatus) {
            var option = ActivityPropertyStatus[i];
            var op = option.split('|');
            op[0] = parseInt(op[0]);
            op[1] = parseInt(op[1]);
            var tmp = (activity.ActivityProperty[i] << op[0]);
            activity.ActivityProperty.status |= tmp;
        }
    },
    //设置选择框被选中
    SetCheck: function (check) {
        if (check != undefined) {
            if (!check.is(":checked")) {
                check.click();
            }
        }
    },
    //取消选择框选中
    SetUnCheck: function (check) {
        if (check != undefined) {
            check.attr("checked", false);
        }
    }
}
var ReturnProperty = {

    ActivityProperty: {
        CanReturnRule: {
            'title': "可退回节点",
            'control': $('<select id="selectCanReturnRule" multiple="multiple" style="width: 100%;height: 267px">')
        },
        ReturnRule: {
            'title': "退回节点",
            'control': $('<select id="selectReturnRule" multiple="multiple" style="width: 100%;height: 267px">')
        }

    },

    InitialPage: function (parent, activity) {
        this.activity = activity;
        this.InitialControl(parent);
        this.InitialData(activity);
    },
    InitialControl: function (parent) {
        parent.empty();
        var that = this;
        var form = $('<form class="form-horizontal" role="form">');
        var btnRight, btnLeft;
        form.append(
            $('<div class="form-group">').append(
                $('<div class="col-sm-4 col-sm-offset-2"   >').append(
                    $('<span>').html(that.ActivityProperty.CanReturnRule.title)
                )
            ).append(
                $('<div class="col-sm-4 col-sm-offset-2" >').append(
                    $('<span>').html(that.ActivityProperty.ReturnRule.title)
                )
            )
        ).append(
            $('<div class="form-group">').append(
                $('<div class="col-sm-5" >').append(
                    that.ActivityProperty.CanReturnRule.control
                )
            ).append(
                $('<div class="col-sm-2" style="vertical-align: middle;height: 100%">').append(
                    btnRight = $('<input class="btn btn-blue" type="button"  style="width: 100%;margin-top: 80px" value=">>>>>>">')
                ).append(
                    btnLeft = $('<input class="btn btn-blue" type="button"   style="width: 100%; margin-top: 20px"  value="<<<<<<">')
                )
            ).append(
                $('<div class="col-sm-5" >').append(
                    that.ActivityProperty.ReturnRule.control
                )
            )
        )

        btnRight.click(function () {
            var query = $('#selectCanReturnRule option:selected')
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.ReturnRule.control.append($(val));
            })
        })
        btnLeft.click(function () {
            var query = $("#selectReturnRule  option:selected");
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.CanReturnRule.control.append($(val));
            })
        })
        parent.append(form);

    },
    //初始化数据（给控件绑定数据）
    InitialData: function (activity) {
        var me = this;
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        wf.activityHelper.GetReturnActivitys(wf.activityHelper.DraftingActivity);
        // me.activity.GetReturnActivitys(true, me.activity.ID);
        if (activity.ActivityProperty != undefined && activity.ActivityProperty.WF_RULE != undefined) {
            //待选择项
            var tmp = new Array();
            for (i = 0; i < me.activity.Preactivity.length; i++) {
                if (me.activity.Preactivity[i].activityType != ActivityType.condition && me.activity.Preactivity[i].activityType != ActivityType.merging && me.activity.Preactivity[i].activityType != ActivityType.branching)
                    if (activity.ActivityProperty.WF_RULE.first(me.activity.Preactivity[i].guid, 'toGuid') == undefined)
                        tmp[tmp.length] = me.activity.Preactivity[i];
            }
            $.each(tmp, function (i, val) {
                if (val.guid != me.activity.guid) {
                    var option = $("<option value=" + val.guid + " title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.CanReturnRule.control.append(option);
                }
            });

            tmp = new Array();
            for (j = 0; j < activity.ActivityProperty.WF_RULE.length; j++) {
                var preac = me.activity.Preactivity.first(activity.ActivityProperty.WF_RULE[j].toGuid, 'guid');
                if (preac && !tmp.first(preac.guid))
                    tmp[tmp.length] = preac;
            }
            $.each(tmp, function (i, val) {
                var option = $("<option value=" + val.guid + " title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                me.ActivityProperty.ReturnRule.control.append(option);
            });
        } else {
            $.each(me.activity.Preactivity, function (i, val) {
                if (val.activityType != ActivityType.condition && val.activityType != ActivityType.merging && val.activityType != ActivityType.branching) {
                    var option = $("<option value=" + val.guid + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.CanReturnRule.control.append(option);
                }
            });
        }
    },

    //保存数据
    SaveData: function (activity) {
        if (activity.ActivityProperty == undefined)
            activity.ActivityProperty = {};
        activity.ActivityProperty.WF_RULE = new Array();
        var query = $("#selectReturnRule  option");
        var j = 0;
        $.each(query, function (i, val) {
            var rule = new Object();
            rule.guid = Guid.NewGuid();

            rule.templateId = '';
            rule.ruleName = '';
            rule.IS_DEFAULT = 0;
            rule.description = '';
            rule.condition = '';
            rule.coordinate = '';
            rule.fromGuid = activity.guid;
            rule.toGuid = $(val).val();
            rule.ruleType = 0;
            rule.ruleType = 1;
            rule.isDel = 0;
            activity.ActivityProperty.WF_RULE[j] = rule;
            ++j;

        });
        activity.ActivityProperty.ENABLE_RETURN = activity.ActivityProperty.WF_RULE > 0 ? 0 : 1;
    }
}
var UserProperty = {
    ActivityProperty: {
        ParticipantType: {
            'typevalue': ''
        },
        RadioJob: {
            'title': "角色",
            'control': $("<input name='patype' type='radio' value='0' checked='checked'>")
        },
        RadioActivity: {
            'title': "活动",
            'control': $("<input name='patype' type='radio' value='1'>")
        },
        DivJob: {

            'control': $("<div style='width:100%;float:left;'>")
        },
        DivActivity: {

            'control': $("<div  style='width:100%;float:left; display:none;'>")
        },
        CanSelectJob: {
            'title': "可选角色",
            'AddRefresh': true,
            'control': $('<select  multiple="multiple" style="width: 100%;height: 267px">')
        },
        SelectedJob: {
            'title': "已选角色",
            'control': $("<ul style='border:1px solid rgba(0,0,0,.25); height:267px; overflow:auto;list-style: none;line-height: 20px !important; padding:5px 10px; '>")
        },
        CanSelectActivity: {
            'title': "可选步骤",
            'AddRefresh': false,
            'control': $('<select id="selectCanSelectActivity" multiple="multiple"  style="width: 100%;height: 267px">')
        },
        SelectedActivity: {
            'title': "已选步骤",
            'control': $('<select id="selectSelectedActivity" multiple="multiple" style="width: 100%;height: 267px">')
        }
    },

    InitialPage: function (parent, activity) {
        var me = this;
        me.parent = parent;
        me.activity = activity;
        me.InitialControl(parent);
        me.InitialData(activity);
    },
    InitialControl: function (parent) {
        parent.empty();
        var that = this;
        var form = $('<form class="form-horizontal" role="form">'), btnJobRight, btnJobLeft, btnActivityRight, btnActivityLeft, jobArea, activityArea;
        form.append(
            $('<div class="form-group">').append(
                $('<div class="col-sm-4 col-sm-offset-2"   >').append(
                    $('<div class="checkbox">').append(
                        $('<label >').append(
                            $(' <input name="radio"  type="radio" checked="checked" data-index="0">')
                        ).append(
                            $('<span class="text">').html("岗位")
                        )
                    )
                )
            ).append(
                $('<div class="col-sm-4 col-sm-offset-2" >').append(
                    $('<div class="checkbox">').append(
                        $('<label >').append(
                            $(' <input name="radio"  type="radio" data-index="1">')
                        ).append(
                            $('<span class="text">').html("活动节点")
                        )
                    )
                )
            )
        ).append(
            jobArea = $('<div class="form-group">').append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.CanSelectJob.control
                )
            ).append(
                $('<div class="col-sm-2" style="vertical-align: middle;height: 100%">').append(
                    btnJobRight = $('<input class="btn btn-blue" type="button" style="width: 100%;margin-top: 80px" value=">>>>>>">')
                ).append(
                    btnJobLeft = $('<input class="btn btn-blue" type="button" style="width: 100%; margin-top: 20px"  value="<<<<<<">')
                )
            ).append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.SelectedJob.control
                )
            )
        ).append(
            activityArea = $('<div class="form-group" style="display: none">').append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.CanSelectActivity.control
                )
            ).append(
                $('<div class="col-sm-2" style="vertical-align: middle;height: 100%">').append(
                    btnActivityRight = $('<input class="btn btn-blue" type="button" style="width: 100%;margin-top: 80px" value=">>>>>>">')
                ).append(
                    btnActivityLeft = $('<input class="btn btn-blue" type="button" style="width: 100%; margin-top: 20px"  value="<<<<<<">')
                )
            ).append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.SelectedActivity.control
                )
            )
        )
        var radios = $('input[type=radio]', form);
        radios.click(function () {
            $this = $(this);
            var currentDataType = $this.data("index");
            if (currentDataType == 0) {
                activityArea.css('display', 'none');
                jobArea.css('display', 'block');
            } else {
                jobArea.css('display', 'none');
                activityArea.css('display', 'block');
            }
        })
        btnJobRight.click(function () {
            var query = that.ActivityProperty.CanSelectJob.control.find("option:selected");
            $.each(query, function (i, val) {
                $(val).remove();
                that.AppendTableRow($(val).val(), $(val).text(), "", that.ActivityProperty.SelectedJob);
            })
        })
        btnJobLeft.click(function () {
            var query = that.ActivityProperty.SelectedJob.control.find("li");
            $.each(query, function (i, val) {
                if (that.getBackgroundColor($(val)) == '#26a0da') {
                    var participantid = $(val).find("input").eq(0).val();
                    var participantname = $(val).find("span").eq(0).text();
                    var option = $("<option value=" + participantid + " title=" + participantname + ">" + participantname + "</option>");
                    that.ActivityProperty.CanSelectJob.control.append(option);
                    $(val).remove();
                }
            })
        })
        btnActivityRight.click(function () {
            var query = $('#selectCanSelectActivity option:selected')
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.SelectedActivity.control.append($(val));
            })
        })
        btnActivityLeft.click(function () {
            var query = $("#selectSelectedActivity  option:selected");
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.CanSelectActivity.control.append($(val));
            })
        })
        parent.append(form);
    },
    //初始化控件数据
    InitialData: function (activity) {

        var me = this;
        this.ActivityProperty.CanSelectActivity.control.empty();
        this.ActivityProperty.SelectedActivity.control.empty();
        this.ActivityProperty.SelectedJob.control.empty();
        this.ActivityProperty.CanSelectJob.control.empty();
        if (activity.ActivityProperty != undefined && activity.ActivityProperty.activityParticipants && activity.ActivityProperty.activityParticipants.length > 0 &&
            activity.ActivityProperty.activityParticipants[0].type) {
            this.ActivityProperty.ParticipantType.typevalue = activity.ActivityProperty.activityParticipants[0].type;
            if (this.ActivityProperty.ParticipantType.typevalue == "2") {
                this.SetCheck(this.ActivityProperty.RadioActivity.control);

            }
            else {
                this.SetCheck(this.ActivityProperty.RadioJob.control);
            }
        }
        else {
            this.ActivityProperty.ParticipantType.typevalue = "0";
            this.SetCheck(this.ActivityProperty.RadioJob.control);
        }
        this.InitialJobData(activity);
        this.InitialActivityData(activity);
    },

    InitialJobData: function (activity) {
        var me = this;
        var selectedJob = $("#selectSelectedJob option");
        //SqlHelper.GetAllJob();
        $.each(SqlHelper.JobList, function (i, val) {
            if (activity.ActivityProperty != undefined && activity.ActivityProperty.activityParticipants != undefined) {
                var j = 0;
                var bSelected = false;
                for (h = 0; h < activity.ActivityProperty.activityParticipants.length; h++) {
                    if (val.id == activity.ActivityProperty.activityParticipants[h].participantId) {
                        j = h;
                        bSelected = true;
                        break;
                    }
                }
                if (bSelected) {
                    me.AppendTableRow(val.id, val.jobName, activity.ActivityProperty.activityParticipants[j].type, me.ActivityProperty.SelectedJob);
                }
                else {
                    var option = $("<option value=" + val.id + " title=" + val.jobName + ">" + val.jobName + "</option>");
                    me.ActivityProperty.CanSelectJob.control.append(option);
                }
            }
            else {
                var option = $("<option value=" + val.id + " title=" + val.jobName + ">" + val.jobName + "</option>");
                me.ActivityProperty.CanSelectJob.control.append(option);
            }
        });
    },

    InitialActivityData: function (activity) {
        var me = this;
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        wf.activityHelper.GetReturnActivitys(wf.activityHelper.DraftingActivity);
        //me.activity.GetReturnActivitys(true, me.activity.id);
        $.each(me.activity.Preactivity, function (i, val) {
            if (activity.ActivityProperty != undefined && activity.ActivityProperty.activityParticipants != undefined) {
                var j = 0;
                var bSelected = false;
                for (h = 0; h < activity.ActivityProperty.activityParticipants.length; h++) {
                    if (val.id == activity.ActivityProperty.activityParticipants[h].participantId) {
                        j = h;
                        bSelected = true;
                        break;
                    }
                }
                if (bSelected) {
                    var option = $("<option value=" + val.id + "  title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.SelectedActivity.control.append(option);
                }
                else {
                    var option = $("<option value=" + val.id + "  title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.CanSelectActivity.control.append(option);
                }
            }
            else {
                var option = $("<option value=" + val.id + "  title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                me.ActivityProperty.CanSelectActivity.control.append(option);
            }
        });
    },

    SaveData: function (activity) {
        var me = this;

        if (me.ActivityProperty.RadioActivity.control.is(":checked")) {
            me.SaveActivityData(activity);
            activity.ActivityProperty.type = me.ActivityProperty.RadioActivity.control.val();
        }
        else {
            me.SaveJobData(activity);
            activity.ActivityProperty.type = me.ActivityProperty.RadioJob.control.val();
        }
    },

    SaveJobData: function (activity) {
        var me = this;
        activity.ActivityProperty.activityParticipants = new Array();
        var query = me.ActivityProperty.SelectedJob.control.find("li");

        $.each(query, function (i, val) {
            var participantid = $(val).find("input").eq(0).val();
            var participanttype = $(val).find("input[type=radio]").filter(':checked').val();
            activity.ActivityProperty.activityParticipants[activity.ActivityProperty.activityParticipants.length] = me.InitialParticipant(participanttype, participantid);
        })
    },

    SaveActivityData: function (activity) {
        var me = this;
        activity.ActivityProperty.activityParticipants = new Array();
        var query = me.ActivityProperty.SelectedActivity.control.find("option");
        $.each(query, function (i, val) {
            activity.ActivityProperty.activityParticipants[activity.ActivityProperty.activityParticipants.length] = me.InitialParticipant(2, $(val).val());
        })
    },

    InitialParticipant: function (participantType, participantId) {
        var me = this;
        var participant = new Object();

        participant.guid = me.activity.guid;
        participant.type = participantType;
        participant.participantId = participantId;
        participant.isDel = 0;
        return participant;
    },

    AppendTableRow: function (tbvalue, tbname, tbtype, Prop) {
        var me = this, radioPublic, radioPravite;

        var li = $("<li style='height:20px; width:240px; line-height:20px;font-size:12px; display: inline-block '>");
        li.append(
            $('<input style="display:none;" name="participantid"/>').val(tbvalue)
        ).append(
            $('<span style="float:left;  background-color:transparent;">').html(tbname)
        ).append(
            $('<div class="checkbox" style="display: inline-block;padding-top: 0px !important; margin-left: 10px;" >').append(
                $('<label >').append(
                    radioPublic = $('<input name="radio"  type="radio" data-index="0" value="0">').attr('name', tbvalue)
                ).append(
                    $('<span class="text">').html("监管")
                )
            )
        ).append(
            $('<div class="checkbox" style="display: inline-block;padding-top: 0px !important;margin-left: 10px;">').append(
                $('<label >').append(
                    radioPravite = $(' <input name="radio"  type="radio" data-index="1" value="1">').attr('name', tbvalue)
                ).append(
                    $('<span class="text">').html("全局")
                )
            )
        )
        debugger;
        if (tbtype == 0) {
            radioPublic.attr("checked", true);
            radioPravite.removeAttr("checked");
        } else {
            radioPravite.attr("checked", true);
            radioPublic.removeAttr("checked");
        }

        Prop.control.append(li);

        li.bind({
            "click": function (e) {
                if (e.button == 0) {
                    if (!e.ctrlKey) {
                        Prop.control.find("li").css("background-color", "white");
                    }
                    if (me.getBackgroundColor(li) == '#26a0da')
                        li.css("background-color", "white");
                    else
                        li.css("background-color", "#26a0da");
                }
            }, "mouseenter": function () {
                if (me.getBackgroundColor(li) != '#26a0da')
                    li.css("background-color", "#e8e8e8");
            }, "mouseleave": function () {
                if (me.getBackgroundColor(li) != '#26a0da')
                    li.css("background-color", "white");
            }

        });
    },

    SetCheck: function (check) {
        check.click();
    },
    //获取div的背景色
    /*
     不同浏览器获得背景色的表线形式不同
     这里将他们都格式化为 #ffffff 的格式
     */
    getBackgroundColor: function (control) {
        var rgb = control.css('background-color');
        if (rgb.indexOf('#') != -1 || rgb == 'transparent' || rgb == 'white')
            return rgb;
        //rgb(232, 232, 232)
        rgb = rgb.split('(')[1];
        rgb = rgb.substring(0, rgb.length - 1);
        rgb = rgb.split(',');


        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }

        return rgb = "#" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
    }

}
var ruleProperty = {

    RuleProperty: {
        ruleName: {
            'id': 'ruleName',
            'name': 'ruleName',
            'title': "规则名称"
        },
        expression: {
            'id': 'expression',
            'name': 'expression',
            'title': "表达式"
        }
    },
    //初始化页面
    InitialPage: function (parent, rule) {
        this.rule = rule;
        this.InitialControl(parent);
        this.InitialData(rule);
    },
    //初始化数据
    InitialData: function (rule) {
        var me = this;
        if (rule.RuleProperty != undefined) {
            me.RuleProperty.ruleName.control.val(rule.RuleProperty.ruleName);
            me.RuleProperty.expression.control.val(rule.RuleProperty.expression);
        }
    },

    InitialControl: function (parent) {
        parent.empty();
        var form = $('<form class="form-horizontal" role="form">');
        parent.append(form);
        form.append(
            $('<div class="form-group">').append(
                label(this.RuleProperty.ruleName, 2)
            ).append(
                input(this.RuleProperty.ruleName, 10)
            )
        ).append(
            $('<div class="form-group">').append(
                label(this.RuleProperty.expression, 2)
            ).append(
                input(this.RuleProperty.expression, 10)
            )
        )
        function label(data, column, offset) {
            var result = $($.format('<label class="col-sm-{0} col-sm-offset-{1} control-label no-padding-right">', column, offset == undefined ? 0 : offset)).html(data.title)
                .attr('class', 'col-sm-2 control-label no-padding-right').attr('for', data.name)
            return result;
        }

        function input(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                data.control = $('<input class="form-control" type="text">').attr('id', data.id).attr('name', data.name).attr('placeholder', data.title)
            )
            return result;
        }
    },
    //保存数据
    SaveData: function (rule) {
        var me = this;
        if (rule.RuleProperty == undefined) {
            rule.RuleProperty = {};
        }
        rule.RuleProperty.ruleName = me.RuleProperty.ruleName.control.val();
        rule.RuleProperty.expression = me.RuleProperty.expression.control.val();
    }
}
var Reflection = {
    'BaseProperty': BaseProperty,
    'UserProperty': UserProperty,
    'ReturnProperty': ReturnProperty
}
var Property = {
    InitailProperty: function (activity) {
        var root = $('#root');
        var container = $('.tabbable', root);
        container.empty();
        var ul = $('<ul class="nav nav-tabs" id="tabNav">');
        var content = $('<div class="tab-content">');
        var activityType = activity.GetActivityTypeName()
        var tmp = 0;
        $.each(PropertyConfig[activityType], function (i, val) {
            var id = Guid.NewGuid();
            var li = $('<li>');
            var property;
            if (tmp == 0) {
                li.attr('class', 'active').append($('<a aria-expanded="true" data-toggle="tab">').html(val.description).attr('href', '#' + id));
                property = $(' <div class="tab-pane in active">').attr('id', id);
                content.append(property);
            } else {
                li.attr('class', 'tab-red').append($('<a aria-expanded="false" data-toggle="tab">').html(val.description).attr('href', '#' + id));
                property = $(' <div class="tab-pane">').attr('id', id);
                content.append(property);
            }
            ul.append(li);
            Reflection[val.js]["InitialPage"](property, activity);
            property.unbind();
            ++tmp;
        });
        container.append(ul);
        container.append(content);
        $('.widget-caption', root).html(activity.ActivityName);
        return root;
    },
    SaveData: function (activity) {
        debugger;
        var activityType = activity.GetActivityTypeName()
        $.each(PropertyConfig[activityType], function (i, val) {
            Reflection[val.js].SaveData(activity);
        });
    }
}
//鼠标事件
var MouseOperation = function () {
    var isActivityMove = false;
    var isRuleMove = false;
};
MouseOperation.prototype = {
    //leftbuttondown  单击

    leftbuttondown: function (e) {
        $.each(wf.activityHelper.Activitys, function (i, activity) {
            activity.isSelect = 0;
        });
        $.each(wf.rules, function (a, val) {
            val.isSelect = false;
        })
        //添加节点，
        if (wf.gcommand == Command.addactivity) {
            wf.activityHelper.AddActivity(wf.canvasHelper.GetPoint(e), wf.currentActivityType);
        }
        else if (wf.gcommand == Command.addrules) {
        }
        //选择操作
        else {
            //1、获得可能选中的节点
            var result = wf.canvasHelper.GetSelectedActivity(e);
            /*result.isSelect：true 有节点被选中
             false没有节点被选中
             */
            if (result.isSelect) {
                result.selectedObject.isSelect = 3;
                if (wf.selectedObjects.length > 0 && wf.selectedObjects.contains(result.selectedObject)) {
                    $.each(wf.selectedObjects, function (i, val) {
                        val.currentActivityPosition = val.position;
                        val.startMovePoint = wf.canvasHelper.GetPoint(e);
                    });
                    wf.moveActivity = true;
                } else {
                    //清除样式
                    wf.canvasHelper.ClearAllStyle();
                    result.selectedObject.SelectActivity(e, result.distinct);
                }
            } else {

                wf.selectedObjects = new Array();
                result = wf.canvasHelper.GetSelectedRule(e);
                //1、是否有规则被选中
                if (result.isSelect) {
                    wf.workspace.css("cursor", "pointer");
                    result.selectedObject.isSelect = true;
                    wf.currentRule = result.selectedObject;
                    wf.currentRule.SelectRule(result);
                    wf.canvasHelper.ClearAllStyle();
                } else {
                    //没有任何单元被选中
                    wf.canvasHelper.ClearAllStyle();
                    wf.gcommand = Command.nulloperation;
                }
            }
        }
    },
    //鼠标左键弹起事件
    leftbuttonUp: function (e) {
        var me = this;
        if (!e.ctrlKey) {
            wf.selectedObjects = new Array();
        }
        var result = wf.canvasHelper.GetSelectedActivity(e);
        switch (wf.gcommand) {
            case Command.addrules:
                if (result.isSelect) {
                    if (result.selectedObject != wf.currentRule.startActivity && result.selectedObject.CanHaveToRule()) {
                        wf.canvasHelper.AddRule(wf.currentRule, result.selectedObject);
                    }
                }
                else
                    wf.currentRule.AddPoint(wf.canvasHelper.GetPoint(e));
                break;
            case   "approval":
                wf.gcommand = Command.nulloperation;
                break;
            case Command.selectactivity:
                wf.moveActivity = false;
                if (wf.currentActivity.capture.iscapture)
                    wf.currentActivity.MoveActivity(wf.currentActivity.capture.point, 'tra');
                if (me.isActivityMove) {
                    me.isActivityMove = false;
                }
                wf.currentActivity.ResetActivity();
                break;
        }
        if (wf.moveRule) {
            wf.currentRule.ChangeActivity(wf.canvasHelper.GetPoint(e), result);
            if (me.isRuleMove) {
                isRuleMove = false;
            }
            wf.moveRule = false;
        }
        wf.workspace.css("cursor", "default");

    },
    //鼠标移动
    mouseMove: function (e) {
        if (document.getBoxObjectFor) {
            alert("");
        }
        var me = this;
        var point = wf.canvasHelper.GetPoint(e);
        if (wf.gcommand == Command.addrules) {
            if (!wf.currentRule.startActivity.Picture.isPointInPath(e.offsetX, e.offsetY)) {
                var currentPoint = wf.canvasHelper.GetPoint(e);
                if (wf.currentRule.capture.iscapture)
                    currentPoint = wf.currentRule.capture.point
                wf.currentRule.DrawRule(currentPoint);
                wf.currentRule.DrawReferenceLine(point);
            }
        } else if (wf.gcommand == Command.addactivity) {

        } else if (wf.moveActivity) {
            if (wf.selectedObjects.length == 0) {
                wf.currentActivity.MoveActivity(point);

                wf.currentActivity.DrawReferenceLine(point);
                me.isActivityMove = true;
            }
            else {
                $.each(wf.selectedObjects, function (i, val) {
                    val.MoveActivity(point);
                });
            }
        }
        else if (wf.moveRule) {
            wf.currentRule.ResetPoint(e);
            me.isRuleMove = true;
        }
        else {
            var result = wf.canvasHelper.GetSelectedActivity(e);
            $.each(wf.activityHelper.Activitys, function (i, activity) {
                if (activity.isSelect < 3)
                    activity.isSelect = 0;
                activity.isDrawRuleStart = false;
            });

            if (result.isSelect) {

                if (result.distinct > 10) {
                    wf.workspace.css("cursor", "pointer");
                    if (result.selectedObject.isSelect != 3)
                        result.selectedObject.isSelect = 1;
                }
                else if (result.selectedObject.CanHaveFromRule()) {
                    wf.workspace.css("cursor", "crosshair");
                    result.selectedObject.isDrawRuleStart = true;
                    if (result.selectedObject.isSelect != 3)
                        result.selectedObject.isSelect = 2;
                }

            }
            else {
                $.each(wf.activityHelper.Activitys, function (i, activity) {
                    if (activity.isSelect < 3)
                        activity.isSelect = 0;
                });
                result = wf.canvasHelper.GetSelectedRule(e);
                if (result.isSelect)
                    wf.workspace.css("cursor", "pointer");
                else
                    wf.workspace.css("cursor", "default");
            }
            wf.canvasHelper.ClearAllStyle();
        }
    },
    //鼠标右键
    rightbuttondown: function (e) {
        if (wf.gcommand == Command.addrules) {
            wf.currentRule.Dispose();
            wf.gcommand = Command.nulloperation;
        } else if (wf.gcommand == Command.addactivity) {
            wf.gcommand = Command.nulloperation;

        }

        return false;
    },

    ctrlKeybuttondown: function (e) {

        if (wf.selectedObjects.length == 0 && wf.gcommand == Command.selectactivity) {
            wf.selectedObjects[0] = wf.currentActivity;
        }
        var result = wf.canvasHelper.GetSelectedActivity(e);
        if (result.isSelect) {
            wf.selectedObjects[wf.selectedObjects.length] = result.selectedObject;
            result.selectedObject.SelectActivity(e, result.distinct);
            $.each(wf.selectedObjects, function (i, val) {
                val.currentActivityPosition = val.position;
                val.startMovePoint = wf.canvasHelper.GetPoint(e);
            });
        }
    },
    //左键双击
    leftbuttondoubleclick: function (e) {
        var result = wf.canvasHelper.GetSelectedActivity(e);
        if (result.isSelect) {
            if (wf.gcommand == Command.addrules)
                this.rightbuttondown();
            //显示节点属性
            result.selectedObject.ShowProperty();

        }
        else {
            result = wf.canvasHelper.GetSelectedRule(e);
            if (result.isSelect) {
                //显示规则线属性
                result.selectedObject.ShowProperty();
            }
        }
        return false;
    }
}
/*
toolbar
 */
var toolbar = {
    islock: false,
    isdblclick: false,
    config: {
        file: {
            description: '文件 ',
            items: {
                save: {id: 'save', img: 'save.png', tag: '保存'}
            }
        },
        edit: {
            description: '编辑',
            items: {
                lock: {id: 'lock', img: 'lock.png', tag: '加锁'}
            }
        },
        activity: {
            description: '节点',
            items: {
                approval: {id: 'approval', img: 'approval.png', tag: '决策'},
                condition: {id: 'condition', img: 'condition.png', tag: '条件'},
                freedom: {id: 'freedom', img: 'freedom.png', tag: '自由'}
            }
        }
    },
    init: function (element) {
        $.each(toolbar.config, function (j, menu) {
            // var split = $("<li>").attr("class", "group").html(menu.description);
            // element.append(split);

            $.each(menu.items, function (i, val) {
                var image = $('<img>').attr('src', '/assets/js/workflow/images/toolbar/' + val.img);
                var li = $("<li>").dblclick(function () {
                    toolbar.isdblclick = true;
                    toolbar.mousedownCallBack(i);
                }).click(function () {
                    isDoubleClickCommand = false;
                    toolbar.mousedownCallBack(i, image);
                }).append(image).append(val.tag);
                if (Command[i] == Command.lock) {
                }
                element.append(li)
            });
        });
    },
    mousedownCallBack: function (cmd, image) {
        var me = this;
        var tmp = Command.create;
        if (cmd in Command)
            tmp = Command[cmd];
        if (tmp == Command.create || tmp == Command.open || tmp == Command.export || tmp == Command.import) {
            switch (Command[cmd]) {
                case Command.create:
                    me.Create();
                    break;
                case Command.open:
                    me.Open();
                    break;
                case Command.import:
                    me.Import();
                    break;
            }
        }
        if (me.CanOperation) {
            if (cmd in ActivityType) {
                wf.gcommand = Command.addactivity;
                wf.currentActivityType = ActivityType[cmd];
                wf.workspace.css("cursor", "crosshair");
            }
            else {
                switch (Command[cmd]) {
                    case Command.addrules:
                        wf.gcommand = cmd;
                        break;
                    case Command.save:
                        SqlHelper.GetAllPackage(me.Save);
                        break;
                    case Command.lock:
                        me.Edit(image);
                        break
                    case Command.undo:
                        me.UndoCommand();
                        break;
                    case Command.redo:
                        me.RedoCommand();
                        break;
                    case Command.export:
                        me.Export();
                        break;
                }
            }
        }
    },
    Create: function (templateId) {
        var me = this;
        var layerNum = $.layer({
            type: 1,
            title: false,
            move: [$("#divorgTitle"), true],
            fix: false,
            closeBtn: true,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['360px', '420px'],
            page: {dom: $("#divOrg")},
            success: function () {
            }
        });
        $(".xubox_main").css("background-color", "transparent");
        OrgHelper.BindOrg(SqlHelper.OrgList);
        $("#btnCreateOK").unbind();
        $("#btnCreateCancel").unbind();
        $("#btnCreateOK").click(function () {

            var nodes = zTreeObj.getSelectedNodes();
            if (nodes.length > 0) {
                wf.orgId = nodes[0].id;
                SqlHelper.GetAllJob();
                canvasHelper.CreateTemplate();
                layer.close(layerNum);
                me.CanOperation = true;
                me.UnBind();

                //wf.canvas.unbind();
                //wf.canvas.dblclick(function (e) {
                //    e.stopPropagation();
                //    wf.mouseOperation.leftbuttondoubleclick(e);

                //});

                me.BindEvent();
                templateStatus = TemplateStatus.New;
                template = {id: templateId ? templateId : undefined};
                $("#divTemplateName").css('display', 'none');
            }
        });
        $("#btnCreateCancel").click(function () {
            layer.close(layerNum);
        });

    },
    Save: function (data) {
        debugger;
        var me = toolbar;
        $("#selectPackage").html("");
        $("#btnNewVersion").unbind();
        $("#btnEdit").unbind();
        $("#btnSaveOK").unbind();
        $("#btnSaveCancel").unbind();


        var package_id = template == undefined || template.id == undefined || template.id == null ? "" : template.id;


        $.each(data, function (i, val) {
            var option = package_id == val.id ? $("<option selected='selected'  value='" + val.id + "' >" + val.packageName + "</option>") : $("<option  value='" + val.id + "' >" + val.packageName + "</option>");
            $("#packageName").append(option);
        });

        var tmpName = template == undefined || template.templateName == undefined || template.templateName == null ? "" : template.templateName;
        $("#templateName").val(tmpName);
        var description = template == undefined || template.description == undefined || template.description == null ? "" : template.description;
        $("#description").val(description);

        $("#txtImg").val(template.imgurl || "");
        $("#templateName").val(tmpName);

        $('#save').modal();

        switch (wf.templateStatus) {
            case TemplateStatus.New:
                $("#btnNewVersion").css("display", "none");
                $("#btnEdit").css("display", "none");
                $("#btnSaveOK").click(function () {
                    template.guid = Guid.NewGuid();
                    template.publisType = 0;
                    me.SaveInvoke();
                });
                break;
            case TemplateStatus.Open:
                $("#btnNewVersion").css("display", "inline");
                $("#btnEdit").css("display", "inline");
                $("#btnNewVersion").click(function () {
                    template.publisType = 2;
                    me.ChangeID();
                    me.SaveInvoke();

                });
                $("#btnEdit").click(function () {
                    if (confirm('修改当前版本可能导致监控图显示不正确,是否继续？')) {
                        template.publisType = 1;
                        me.SaveInvoke();
                    }
                });
                $("#btnSaveOK").click(function () {
                    template.guid = Guid.NewGuid();
                    template.publisType = 0;
                    me.ChangeID();
                    me.SaveInvoke();
                });

                break;
            case TemplateStatus.Import:
                $("#btnNewVersion").css("display", "none");
                $("#btnEdit").css("display", "none");
                $("#btnNewVersion").click(function () {
                    me.ChangeID();
                    me.SaveInvoke('Workflow_AddTemplate');
                });
                $("#btnEdit").click(function () {
                    me.ChangeID();
                    template.versionNum += 1;
                    me.SaveInvoke('Workflow_UpdateTemplate');
                });
                $("#btnSaveOK").click(function () {

                    template.versionNum = 0;
                    me.ChangeID();
                    me.SaveInvoke('Workflow_AddTemplate');
                });
                break;
        }
    },
    //调用保存
    SaveInvoke: function () {
        debugger;
        var me = toolbar;
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        wf.activityHelper.GetReturnActivitys(wf.activityHelper.DraftingActivity);
        var result = {
            result: true,
            errorMessage: ''
        }
        $.each(wf.activityHelper.Activitys, function (i, val) {
            var tmp = val.Validate(wf.activityHelper.DraftingActivity, wf.activityHelper.EndActivity);
            if (!tmp.result) {
                result.result = false;
                result.errorMessage += tmp.errorMessage;
            }
        });

        if (result.result) {
            if (template.versionId == undefined) {
                template.versionId = template.id;
                template.versionNum = 0;
            }
            template.packageId = $("#packageName option:selected").val();
            template.orgId = wf.orgId;
            template.templateName = $("#templateName").val();
            template.description = $("#description").val();
            template.imgurl = $("#txtImg").val();
            $.request('/workflow/template/publish', template, function () {
                alert("成功");
                templateStatus = TemplateStatus.Open;
                SqlHelper.GetAllTemplate({packageName: '', id: ''});
                $('#save').modal('hide');
            });

        }
        else {
            alert(result.errorMessage);
        }
    },
    ChangeID: function () {
        template.guid = Guid.NewGuid();
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.ChangeID();
        });
        $.each(wf.rules, function (i, val) {
            val.ChangeID();
        });
    },
    Open: function () {
        var me = this;
        var layerNum = $.layer({
            type: 1,
            title: false,
            move: [$("#divOpenTitle"), true],
            fix: false,
            closeBtn: true,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['750px', '400px'],
            page: {dom: $("#divOpen")},
            success: function () {
            }
        });
        $(".xubox_main").css("background-color", "transparent");
        OrgHelper.BindOrgForOpen(SqlHelper.OrgList);


        $("#btnOpenOK").unbind();
        $("#btnOpenCancel").unbind();
        $("#btnOpenOK").click(function () {
            if (openTemplateId == undefined || openTemplateId == null || openTemplateId.length == 0) {
                alert("请选择一个模板！");
                return;
            }

            wf.mask.css("display", "block");
            layer.close(layerNum);
            setTimeout(me.Wait, 100);

        })
        $("#btnOpenCancel").click(function () {
            layer.close(layerNum);
        })
    },
    wait: function () {
        var me = this;
        template = SqlHelper.GetTemplateById(openTemplateId);
//编辑
        if (template.activities) {
            wf.orgId = template.orgId;
            SqlHelper.GetAllJob();
            this.load(template);
            this.CanOperation = true;
            this.islock = true;
            // toolbar.Edit(undefined);
            wf.templateStatus = TemplateStatus.Open;
            wf.openTemplateId = null;
            wf.mask.css("display", "none");
        } else {
            //新增
            wf.orgId = app.baseorgId;
            SqlHelper.GetAllJob();
            wf.canvasHelper.CreateTemplate();
            me.CanOperation = true;
            me.UnBind();

            //myCanvas.unbind();
            //myCanvas.dblclick(function (e) {
            //    e.stopPropagation();
            //    wf.mouseOperation.leftbuttondoubleclick(e);

            //});

            me.BindEvent();
            templateStatus = TemplateStatus.New;
            template = pageParm.template;
            template.insert = false;
            $("#divTemplateName").css('display', 'none');
        }
    },
    Edit: function (image) {
        if (image == undefined) image = me.lockImage;
        this.islock = !this.islock;
        if (this.islock) {
            image.attr("src", "/assets/js/workflow/images/toolbar/unlock.png");
            this.UnBind();
            wf.canvas.dblclick(function (e) {
                wf.mouseOperation.leftbuttondoubleclick(e);
            });
        }
        else {
            this.UnBind();
            this.BindEvent();
            image.attr("src", "/assets/js/workflow/images/toolbar/lock.png");
        }
    },
    UnBind: function () {
        wf.workspace.unbind();
        $(document).unbind("keydown");
        wf.canvas.unbind();
    },
    BindEvent: function () {
        var me = this;
        wf.canvas.mousedown(function (e) {
            if (e.button == 0) {
                if (e.ctrlKey) {
                    wf.mouseOperation.ctrlKeybuttondown(e);
                }
                else {
                    wf.mouseOperation.leftbuttondown(e);
                }
            }
            else if (e.button = 1) {
                wf.mouseOperation.rightbuttondown(e);
            }
        }).mouseup(function (e) {
                if (e.button == 0)
                    wf.mouseOperation.leftbuttonUp(e);
            }
        ).mousemove(function (e) {
            wf.mouseOperation.mouseMove(e);
        });
        var isctrlKey = false;
        $(document).keydown(
            function (e) {
                if (e.keyCode == 17) isctrlKey = true;
                if (isctrlKey && e.keyCode == 90)
                    me.UndoCommand();
                else if (isctrlKey && e.keyCode == 89)
                    me.RedoCommand();
                else {
                    switch (e.keyCode) {
                        case 46:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.Dispose();
                                });
                                wf.selectedObjects = new Array();
                            }
                            else if (wf.gcommand == Command.selectactivity)
                                wf.currentActivity.Dispose();
                            else if (wf.gcommand == Command.selectrule)
                                wf.currentRule.Dispose();
                            break;
                        case 38:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X, val.position.Y - 1), true);
                                });
                            }
                            else if (wf.gcommand == Command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X, wf.currentActivity.position.Y - 1), true);
                            return false;

                        case 40:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X, val.position.Y + 1), true);
                                });
                            }
                            else if (wf.gcommand == Command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X, wf.currentActivity.position.Y + 1), true);
                            return false;
                        case 37:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X - 1, val.position.Y), true);
                                });
                            }
                            else if (wf.gcommand == Command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X - 1, wf.currentActivity.position.Y), true);
                            return false;
                        case 39:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X + 1, val.position.Y), true);
                                });
                            }
                            else if (wf.gcommand == Command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X + 1, wf.currentActivity.position.Y), true);
                            return false;

                    }
                }
            }
        );
        wf.workspace.keyup(function () {
            ctrlKey = false;
        })


        wf.canvas.dblclick(function (e) {
            wf.mouseOperation.leftbuttondoubleclick(e);
        });


    },
    load: function (tmp, isImport) {
        debugger;
        template = tmp;
        if (template.templateName) {

        }
        if (wf.activityHelper == undefined)
            wf.activityHelper = new ActivityHelper();
        else {
            wf.activityHelper.Dispose();
            wf.activityHelper = new ActivityHelper();
        }


        $.each(template.activities, function (i, val) {
            if (val.isDel == 0) {
                var activity_coordinate = val.coordinate.split('$');
                var position = new Point(activity_coordinate[0], activity_coordinate[1]);
                var activity = wf.activityHelper.AddActivity(position, val.activityType, true);
                activity.id = val.id;
                if (val.activityType == ActivityType.start)
                    wf.activityHelper.StartActivity = activity;
                else if (val.activityType == ActivityType.end)
                    wf.activityHelper.EndActivity = activity;
                else if (val.activityType == ActivityType.drafting)
                    wf.activityHelper.DraftingActivity = activity;

                activity.isSelect = 0;
                val.guid = activity.guid;
                val.insert = 0;
                activity.SetProperty(val);
                activity.ResetActivity();
            }
        });

        $.each(template.rules, function (i, val) {
            if (val.isDel == 0) {
                val.insert = 0;
                var activity = wf.activityHelper.Activitys.first(val.fromGuid || val.fromActivityId, 'id');
                if (val.ruleType == 0) {
                    if (activity != null) {
                        var rule = new Rule(activity);
                        var position = val.coordinate.split(',');
                        var positionX = position[0].split('$');
                        var positionY = position[1].split('$');
                        if (positionX.length > 2)
                            for (j = 1; j < positionX.length - 1; j++) {
                                rule.AddPoint(new Point(positionX[j], positionY[j]));
                            }
                        var endac = wf.activityHelper.Activitys.first(val.toActivityId || val.fromActivityId, 'id');
                        wf.canvasHelper.AddRule(rule, endac, true);

                        rule.SetProperty(val);
                    }


                }
                else if (!isImport) {
                    if (activity.ActivityProperty.WF_RULE == undefined)
                        activity.ActivityProperty.WF_RULE = new Array();
                    activity.ActivityProperty.WF_RULE[activity.ActivityProperty.WF_RULE.length] = val;

                }
            }
        });

        $.each(wf.activityHelper.Activitys, function (i, val) {
            if (val.activityType == ActivityType.Merging) {
                var branchActivityId = wf.activityHelper.Activitys.first(val.ActivityProperty.branchActivityId);
                val.BranchingControl = branchActivityId;
                branchActivityId.MergingControl = val;
            }
        })


    }
}